Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2bb9c81069 | ||
|
|
cedb51b8ea | ||
|
|
66d13059dd | ||
|
|
800ea40c0d | ||
|
|
20442eecd3 | ||
|
|
22d1cd7032 | ||
|
|
6a0dc18655 | ||
|
|
e006dbf1af | ||
|
|
8241a750fa | ||
|
|
41779cf7bb | ||
|
|
b01b9689c8 | ||
|
|
4426da6f5d | ||
|
|
5ead82e627 | ||
|
|
c29b0d2f13 | ||
|
|
480fd8d517 | ||
|
|
4c09fa5355 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Questions and chat
|
||||
url: https://solidcraft.io/discord
|
||||
about: Ask questions and talk with users and contributors on the SolidCraft Discord.
|
||||
@@ -1,3 +0,0 @@
|
||||
self-hosted-runner:
|
||||
labels:
|
||||
- self-hosted-fast
|
||||
@@ -12,8 +12,6 @@ name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
# The merge queue: each queued group runs the full suite before it lands on main.
|
||||
merge_group:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
@@ -215,8 +213,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install a software Vulkan driver (lavapipe)
|
||||
# Preinstalled on the self-hosted runner, which has no sudo.
|
||||
if: runner.environment == 'github-hosted'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1
|
||||
|
||||
@@ -26,8 +26,6 @@ jobs:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: main
|
||||
# main goes through the merge queue; this deploy key may push past it.
|
||||
ssh-key: ${{ secrets.GENERATED_FILES_DEPLOY_KEY }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
|
||||
with:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# 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
|
||||
# The documentation site on GitHub Pages: the book (docs/book) at /solidcraft/ and the web app
|
||||
# at /solidcraft/app/. Needs Settings → Pages → Source = GitHub Actions; skipped while the
|
||||
# repository is private.
|
||||
name: Pages
|
||||
|
||||
@@ -56,7 +56,7 @@ jobs:
|
||||
run: cargo xtask book
|
||||
- name: Build the web app
|
||||
working-directory: apps/solidcraft-web
|
||||
run: trunk build --release --public-url ./
|
||||
run: trunk build --release --public-url /solidcraft/app/
|
||||
- name: Test the web app offline and across an update (headless Chrome)
|
||||
run: cargo xtask web-offline-test --site dist/web
|
||||
- name: Assemble the site
|
||||
|
||||
@@ -36,8 +36,6 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/archive/icons/macos-v1/exports/icon.iconset/icon_256x256@2x.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | MIT OR Apache-2.0 |
|
||||
| assets/archive/icons/macos-v1/exports/icon.iconset/icon_512x512.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | MIT OR Apache-2.0 |
|
||||
| assets/archive/icons/macos-v1/exports/icon.iconset/icon_512x512@2x.png | SolidCraft contributors | native sips export from assets/archive/icons/macos-v1/exports/icon.png | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/class-a-blend.png | SolidCraft contributors | screenshot of SolidCraft itself: two boxes bridged by `surface.blend` (a 40x10 sheet, `solidcraft-cli snapshot` of plan/evidence script ev_blend) | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/class-a-crown.png | SolidCraft contributors | screenshot of SolidCraft itself: a patch crowned with `surface.patch crown=0.3` over a saddle rim (`solidcraft-cli snapshot`) | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/class-a-boundary.png | SolidCraft contributors | screenshot of SolidCraft itself: a patch through two sketch lines built by `surface.boundary` with `crown: 0.4` (`solidcraft-cli snapshot`) | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/sample-plate.png | SolidCraft contributors | screenshot of SolidCraft itself (`solidcraft --sample`) | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/demo-0.8.gif | SolidCraft contributors | original screen recording of the actual SolidCraft 0.8 English desktop UI modelling an original Raspberry Pi 4 case (no logos or branding; the engraved text is set in the system's DejaVu Sans Bold), generated with examples/demo/record_ui.sh and its original animated pointer overlay (9× playback) | MIT OR Apache-2.0 |
|
||||
@@ -96,11 +94,9 @@ Editable drawing code, native projects and shipped exports are collected under `
|
||||
| assets/locales/de.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/en.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/fr.json | rlartot | French translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/gl.json | Pablo López (pablopeza) | Galician translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/ja.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/ko.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
| assets/locales/ru.json | Alex Pro (del000) | Russian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/pt-BR.json | DuBearte | Brazilian Portuguese translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/tr.json | macrulz54 | Turkish translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/uk.json | Igor Bronovskyi (BrunIF) | Ukrainian translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/zh.json | SolidCraft contributors | Original SolidCraft resource data or drawing code, collected without redesign | MIT OR Apache-2.0 |
|
||||
|
||||
+7
-10
@@ -10,16 +10,13 @@ Help is welcome, whether that's a one-line fix or owning a whole area. This page
|
||||
build it, how the code is laid out, the few rules that aren't negotiable, and where help is
|
||||
needed most.
|
||||
|
||||
Questions, ideas or want to say what you're working on? Join the [Discord](https://solidcraft.io/discord).
|
||||
|
||||
## Get it running (about 10 minutes on a fast machine)
|
||||
|
||||
You need stable Rust 1.95 or newer (required by egui/eframe 0.36). For the web
|
||||
build you also need `rustup target add wasm32-unknown-unknown` and [`trunk`](https://github.com/trunk-rs/trunk)
|
||||
([documentation](https://trunk-rs.github.io/trunk/)).
|
||||
build you also need `rustup target add wasm32-unknown-unknown` and [`trunk`](https://trunkrs.dev).
|
||||
|
||||
```sh
|
||||
git clone https://github.com/tangency-labs/solidcraft && cd solidcraft
|
||||
git clone https://github.com/bherbruck/solidcraft && cd solidcraft
|
||||
cargo run --release -p solidcraft -- --sample # desktop app with a sample part
|
||||
cargo xtask test # unit, engine and UI-scenario tests
|
||||
cargo xtask ci # everything a PR must pass (see below)
|
||||
@@ -248,11 +245,11 @@ and a fresh CI run:
|
||||
|
||||
## Sending a change
|
||||
|
||||
1. Work is tracked in [GitHub issues](https://github.com/tangency-labs/solidcraft/issues), labelled
|
||||
1. Work is tracked in [GitHub issues](https://github.com/bherbruck/solidcraft/issues), labelled
|
||||
by area (`area:kernel`, `area:sketch`, `area:doc`, `area:ui`, `area:infra`). For anything
|
||||
bigger than a bug fix that has no issue yet, open one first. **Claim the issue with a draft
|
||||
PR** before you start, so two people don't build the same thing:
|
||||
- Check nobody has it: `gh pr list -R tangency-labs/solidcraft --state open --search "#N"`.
|
||||
- Check nobody has it: `gh pr list -R bherbruck/solidcraft --state open --search "#N"`.
|
||||
- Branch from the latest `main`, commit `git commit --allow-empty -m "claim: #N"`, push, and
|
||||
open a **draft** PR titled `<summary> (#N)`, e.g. `Fillet: variable radius along a chain (#123)`.
|
||||
- **The lowest-numbered open PR for an issue wins.** If yours lost, close it (or offer to help
|
||||
@@ -300,10 +297,10 @@ long as the change meets the rules above.
|
||||
|
||||
## Where help is wanted most
|
||||
|
||||
**Kernel speed (slow fillets, booleans, STEP):** please don't rewrite the current kernel code for speed; it is being replaced by [solidcore](https://github.com/bherbruck/solidcore) ([progress](https://bherbruck.github.io/solidcore/)). Report slow cases with a file under the `kernel-perf` label, and put kernel effort into solidcore instead. See [#1597](https://github.com/tangency-labs/solidcraft/issues/1597).
|
||||
**Kernel speed (slow fillets, booleans, STEP):** please don't rewrite the current kernel code for speed; it is being replaced by [solidcore](https://github.com/bherbruck/solidcore) ([progress](https://bherbruck.github.io/solidcore/)). Report slow cases with a file under the `kernel-perf` label, and put kernel effort into solidcore instead. See [#1597](https://github.com/bherbruck/solidcraft/issues/1597).
|
||||
|
||||
See the [`help wanted`](https://github.com/tangency-labs/solidcraft/labels/help%20wanted) and
|
||||
[`good first issue`](https://github.com/tangency-labs/solidcraft/labels/good%20first%20issue) labels.
|
||||
See the [`help wanted`](https://github.com/bherbruck/solidcraft/labels/help%20wanted) and
|
||||
[`good first issue`](https://github.com/bherbruck/solidcraft/labels/good%20first%20issue) labels.
|
||||
In order of how much they'd help users:
|
||||
|
||||
1. **Fillet and blend robustness.** Fillets are our own code (truck has no fillet operation).
|
||||
|
||||
Generated
-1
@@ -4215,7 +4215,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"solidcraft-geom",
|
||||
"weezl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -71,8 +71,6 @@ ttf-parser = { version = "0.25", default-features = false, features = ["std"] }
|
||||
# images
|
||||
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
|
||||
png = "0.18.1"
|
||||
# LZW for GIF animations (MIT OR Apache-2.0, pure Rust; already in the tree through image's tiff).
|
||||
weezl = "0.1.12"
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
<p align="center">
|
||||
<img src="assets/icons/app/linux/exports/hicolor/256x256/apps/ai.storyteller.solidcraft.png" width="96" height="96" alt="SolidCraft" />
|
||||
</p>
|
||||
# SolidCraft
|
||||
|
||||
<h1 align="center">SolidCraft</h1>
|
||||
**An open-source parametric 3D CAD application built in pure Rust.**
|
||||
|
||||
<p align="center">
|
||||
<strong>An open-source parametric 3D CAD application built in pure Rust.</strong><br />
|
||||
Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension
|
||||
and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents
|
||||
model through the built-in MCP server.
|
||||
</p>
|
||||
Sketch, constrain, and build solids with a parametric feature timeline. Change a dimension
|
||||
and watch your model rebuild. Run it on your desktop, in your browser, or let AI agents
|
||||
model through the built-in MCP server.
|
||||
|
||||
<div align="center">
|
||||

|
||||
|
||||
*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).*
|
||||
|
||||
## Download
|
||||
|
||||
[![Download for Windows][badge-windows]][windows-msi]
|
||||
[![Download for macOS][badge-macos]][macos-dmg]
|
||||
@@ -19,33 +18,6 @@
|
||||
[![Get it from the Snap Store][badge-snap]][snap-store]
|
||||
[![Try it in your browser][badge-web]][web-app]
|
||||
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://solidcraft.io">Website</a> ·
|
||||
<a href="https://solidcraft.io/download">Download</a> ·
|
||||
<a href="https://solidcraft.io/app">Try it in the browser</a> ·
|
||||
<a href="https://docs.solidcraft.io/">Documentation</a> ·
|
||||
<a href="https://solidcraft.io/discord">Discord</a> ·
|
||||
<a href="https://github.com/bherbruck/solidcore">SolidCore</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/tangency-labs/solidcraft/actions/workflows/ci.yml?query=branch%3Amain"><img src="https://github.com/tangency-labs/solidcraft/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI" /></a>
|
||||
<a href="https://github.com/tangency-labs/solidcraft/releases/latest"><img src="https://img.shields.io/github/v/release/tangency-labs/solidcraft?label=release" alt="Latest release" /></a>
|
||||
<a href="https://github.com/tangency-labs/solidcraft/releases"><img src="https://img.shields.io/github/downloads/tangency-labs/solidcraft/total?label=downloads" alt="Downloads" /></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/github/license/tangency-labs/solidcraft" alt="Licence" /></a>
|
||||
<a href="https://solidcraft.io/discord"><img src="https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white" alt="Discord" /></a>
|
||||
<a href="https://remade.wiki/projects/solidcraft/"><img src="https://remade.wiki/badges/listed-on-remade-classic.svg" alt="Listed on Remade" /></a>
|
||||
<a href="https://github.com/tangency-labs/solidcraft/stargazers"><img src="https://img.shields.io/github/stars/tangency-labs/solidcraft?style=flat" alt="Stars" /></a>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
*A Raspberry Pi 4 case from an empty design: a sketch dimensioned with the board's parameters, extrude, fillet, shell, the rim rounded in one pick, an M2.5 standoff patterned on the 58 × 49 mm hole rectangle, port cut-outs, vent slots, "Pi 4" engraved in DejaVu Sans Bold and a PETG material defined in the design, with its mass in Properties, then height 24 → 32 mm in Parameters and it all rebuilds. 9× playback. [Full video](https://github.com/tangency-labs/solidcraft/raw/refs/heads/main/docs/screenshots/demo-0.8.mp4), recorded with the [demo script](examples/demo/record_ui.sh).*
|
||||
|
||||
## Download
|
||||
|
||||
- **Windows:** download and run the [installer][windows-msi].
|
||||
Also for [ARM64][windows-arm64-msi] and [32-bit][windows-x86-msi] PCs, or as a
|
||||
[portable zip][windows-portable] that runs without installing.
|
||||
@@ -55,7 +27,7 @@
|
||||
(Apple silicon and Intel).
|
||||
- **Linux:** download the [AppImage][linux-appimage], allow it to run as a program and open it.
|
||||
Or install the [.deb][linux-deb] (Ubuntu, Debian, Mint) or [.rpm][linux-rpm] (Fedora,
|
||||
openSUSE), or use [Flatpak](https://docs.solidcraft.io/guide/getting-started.html#linux-flatpak).
|
||||
openSUSE), or use [Flatpak](https://bherbruck.github.io/solidcraft/guide/getting-started.html#linux-flatpak).
|
||||
With Snap: `sudo snap install solidcraft` ([Snap Store][snap-store], or the [.snap file][linux-snap]).
|
||||
For ARM64: [AppImage][linux-arm64-appimage], [.deb][linux-arm64-deb], [.rpm][linux-arm64-rpm].
|
||||
- **Web:** [try it in your browser][web-app], no install.
|
||||
@@ -63,41 +35,39 @@
|
||||
The downloads aren't signed yet. On Windows, if SmartScreen warns you, choose **More info**, then
|
||||
**Run anyway**. On macOS, the first time, right-click SolidCraft in Applications and choose **Open**.
|
||||
|
||||
Older versions, checksums and other formats are on the [releases page](https://github.com/tangency-labs/solidcraft/releases).
|
||||
Older versions, checksums and other formats are on the [releases page](https://github.com/bherbruck/solidcraft/releases).
|
||||
Install details, upgrading from earlier builds and building from source are in
|
||||
[Getting started](https://docs.solidcraft.io/guide/getting-started.html).
|
||||
[Getting started](https://bherbruck.github.io/solidcraft/guide/getting-started.html).
|
||||
|
||||
[badge-windows]: https://img.shields.io/badge/Windows-Download-0078D6?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0id2hpdGUiPjxwYXRoIGQ9Ik0yIDJoOS41djkuNUgyek0xMi41IDJIMjJ2OS41aC05LjV6TTIgMTIuNWg5LjVWMjJIMnpNMTIuNSAxMi41SDIyVjIyaC05LjV6Ii8%2BPC9zdmc%2B
|
||||
[badge-macos]: https://img.shields.io/badge/macOS-Download-333333?style=for-the-badge&logo=apple&logoColor=white
|
||||
[badge-linux]: https://img.shields.io/badge/Linux-AppImage-E95420?style=for-the-badge&logo=linux&logoColor=white
|
||||
[badge-snap]: https://img.shields.io/badge/Snap-Snap_Store-82BEA0?style=for-the-badge&logo=snapcraft&logoColor=white
|
||||
[badge-web]: https://img.shields.io/badge/Web-Try_in_browser-2EA44F?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCIvPjxwYXRoIGQ9Ik0yIDEyaDIwTTEyIDJhMTUgMTUgMCAwIDEgMCAyME0xMiAyYTE1IDE1IDAgMCAwIDAgMjAiLz48L3N2Zz4%3D
|
||||
[windows-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64.msi
|
||||
[windows-arm64-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-arm64.msi
|
||||
[windows-x86-msi]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x86.msi
|
||||
[windows-portable]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-windows-x64-portable.zip
|
||||
[macos-dmg]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-macos-universal.dmg
|
||||
[linux-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage
|
||||
[linux-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.deb
|
||||
[linux-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.rpm
|
||||
[linux-arm64-appimage]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.AppImage
|
||||
[linux-arm64-deb]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.deb
|
||||
[linux-arm64-rpm]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-aarch64.rpm
|
||||
[linux-snap]: https://github.com/tangency-labs/solidcraft/releases/latest/download/solidcraft-linux-x86_64.snap
|
||||
[windows-msi]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-windows-x64.msi
|
||||
[windows-arm64-msi]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-windows-arm64.msi
|
||||
[windows-x86-msi]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-windows-x86.msi
|
||||
[windows-portable]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-windows-x64-portable.zip
|
||||
[macos-dmg]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-macos-universal.dmg
|
||||
[linux-appimage]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-x86_64.AppImage
|
||||
[linux-deb]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-x86_64.deb
|
||||
[linux-rpm]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-x86_64.rpm
|
||||
[linux-arm64-appimage]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-aarch64.AppImage
|
||||
[linux-arm64-deb]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-aarch64.deb
|
||||
[linux-arm64-rpm]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-aarch64.rpm
|
||||
[linux-snap]: https://github.com/bherbruck/solidcraft/releases/latest/download/solidcraft-linux-x86_64.snap
|
||||
[snap-store]: https://snapcraft.io/solidcraft
|
||||
[web-app]: https://solidcraft.io/app
|
||||
[web-app]: https://bherbruck.github.io/solidcraft/app/
|
||||
|
||||
**Documentation:** the [SolidCraft book](https://docs.solidcraft.io/) (user guide,
|
||||
**Documentation:** the [SolidCraft book](https://bherbruck.github.io/solidcraft/) (user guide,
|
||||
developer guide and command reference; sources in [docs/book](docs/book)).
|
||||
|
||||
**Community:** chat with users and contributors on [Discord](https://solidcraft.io/discord).
|
||||
|
||||
**Status: early but usable for simple parts.** 75 of 76 public reference parts
|
||||
match their analytic or FreeCAD-computed volume, area, centre of mass and bounding box
|
||||
([docs/oracle.md](docs/oracle.md)); the other is a tracked bug.
|
||||
These checks do not establish complete geometric or workflow equivalence. The commands SolidCraft has
|
||||
are listed by area in [docs/features.md](docs/features.md); status and plans are in [ROADMAP.md](ROADMAP.md).
|
||||
Open work and known bugs are in [GitHub issues](https://github.com/tangency-labs/solidcraft/issues),
|
||||
Open work and known bugs are in [GitHub issues](https://github.com/bherbruck/solidcraft/issues),
|
||||
and help is welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## Built with SolidCraft
|
||||
@@ -107,7 +77,7 @@ and help is welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
*SELENE, a scientific rover built entirely through SolidCraft's MCP server by
|
||||
[@0xlillith](https://github.com/0xlillith/solidcraft-rover): 3,323 editable timeline steps that
|
||||
rebuild with no errors, replayed here at 2× speed.
|
||||
[Full video](https://github.com/tangency-labs/solidcraft/raw/refs/heads/main/docs/screenshots/rover-build.mp4)
|
||||
[Full video](https://github.com/bherbruck/solidcraft/raw/refs/heads/main/docs/screenshots/rover-build.mp4)
|
||||
· [download the editable model](https://github.com/0xlillith/solidcraft-rover/releases/tag/v1.0.0).*
|
||||
|
||||
## What works
|
||||
@@ -222,12 +192,8 @@ With 3DxWare on Windows, SolidCraft follows 3DxWare's profile for it when there
|
||||
3DxWare's object mode (tilt to roll, twist to spin) until there is. The mouse-wheel turns that
|
||||
3DxWare makes from the cap's motion are ignored, so the view doesn't zoom in steps as the cap tilts.
|
||||
|
||||
On Linux SolidCraft reads the 3D mouse through `spacenavd` when that daemon runs (its socket
|
||||
`/var/run/spnav.sock`), so what you set in `spnavcfg` (swapped or inverted axes, sensitivity, dead
|
||||
zones) applies as it does in other programs, and no udev rule is needed. With nothing set there,
|
||||
the motion is the same as without the daemon. Without `spacenavd`, SolidCraft reads `/dev/hidrawN`
|
||||
directly, so the logged-in user needs access to the device. A udev rule that adds the `uaccess`
|
||||
tag does that, for example
|
||||
On Linux SolidCraft reads `/dev/hidrawN` directly, so the logged-in user needs access to the
|
||||
device. A udev rule that adds the `uaccess` tag does that, for example
|
||||
`/etc/udev/rules.d/70-3d-mouse.rules` for devices with 3Dconnexion's vendor id:
|
||||
|
||||
```
|
||||
|
||||
+6
-15
@@ -53,8 +53,11 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.
|
||||
| M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 |
|
||||
| M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator; taper handle open), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 |
|
||||
| M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 |
|
||||
| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two boundaries exact, three/four refused pending a Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), and every remaining #757–#772 item | deferred | — |
|
||||
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
|
||||
| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops of any shape and number of sides as one face, G0/G1/G2 to the faces beside each edge, through points, #759), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | deferred | — |
|
||||
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
|
||||
| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane or a face), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis. Proposed, in order: surface Extrude/Revolve/Sweep/Loft from open and closed curves (#757), Offset surface (#758), Unstitch and Reverse Normal (#766), Delete Face without healing (#768); Extend curved faces and edges (#760), mutual trim and trim by projected curves (#767), Untrim (#761), Thicken every surface kind (#765); Ruled (#762), Boundary surface and curve networks with G0/G1/G2 (#763), Patch with G1/G2 and general loops (#759), Blend surface (#764), sweep guide rails and two-rail sweeps (#771; orientation, twist and end scale done; loft rails #201), fillet between surface bodies (#769); continuity analysis, surface curvature combs and isocurves (#770) | deferred | — |
|
||||
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Motion Trace (a picked point's path as a joint is driven or a study plays, closed loops following; kept as a 3D sketch spline), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Gear, Rack and Pinion, Screw and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
|
||||
| M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), gears, rack and pinion and screws (motion links whose ratio follows picked radii, parameters or a pitch, also inside closed loops), inverse kinematics (`joint.reach`: a part's point to a target through the joints on its chain, within limits and with loops closed, nearest pose and its stopper when out of reach; dragging a jointed part in the viewport moves it as far as its joints allow), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Gear, Rack and Pinion, Screw and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 |
|
||||
| M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs in Fusion's layout with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 |
|
||||
| M11 | 2D drawings | deferred | — |
|
||||
| M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 |
|
||||
@@ -68,23 +71,11 @@ retain their saved two-finger scroll preference; camera motion is available thro
|
||||
|
||||
M11 precursor: File → Export Current View as DXF exports shown placed bodies from the current
|
||||
camera as a 2D millimetre drawing, with hidden edges omitted or dashed. Vector occlusion splits
|
||||
partly hidden edges and includes curved silhouettes. Repeated part meshes and triangle
|
||||
hierarchies are shared; bounded desktop preparation and occlusion use up to eight workers.
|
||||
Curves are approximated; drawing sheets,
|
||||
partly hidden edges and includes curved silhouettes. Curves are approximated; drawing sheets,
|
||||
annotations and exact projected curves remain deferred. See [view DXF](docs/view-dxf.md).
|
||||
|
||||
Desktop view DXF export runs in the file-operation worker with five-stage progress and
|
||||
cooperative cancellation. Curve tolerance (0.0001–1 mm, default 0.01 mm) is remembered alongside
|
||||
the hidden-edge setting. Cancelled exports preserve the model and the previous destination;
|
||||
completed drawings publish atomically. The browser still exports synchronously.
|
||||
|
||||
## Interactive modelling
|
||||
|
||||
- Thread resolves a suggested metric size when a cylindrical face is picked. Diameter and
|
||||
pitch selectors expose the existing metric designation parameter; custom designations stay
|
||||
editable, and Automatic size returns to the face's suggestion. Cosmetic/modelled and
|
||||
full/partial-length options remain available. This does not add tolerance classes or
|
||||
left-hand threads.
|
||||
- New Body extrusion and face-offset previews show completed intermediate geometry while a
|
||||
drag continues, then catch up to the exact final value. Changes to the selected geometry,
|
||||
operation or feature still discard obsolete results. Distance arrows and their value boxes
|
||||
|
||||
@@ -1519,6 +1519,7 @@ fn sketches_on_loft_and_sweep_faces() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "fails until #562 is fixed"]
|
||||
fn press_pull_on_the_pi_case_floor() {
|
||||
reproduces(
|
||||
Some("tests/action_matrix/designs/pi-case.solidcraft"),
|
||||
@@ -1559,6 +1560,7 @@ fn a_sketch_on_the_rim_a_shell_leaves() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "fails until #565 is fixed"]
|
||||
fn sketches_after_split_body_and_intersect() {
|
||||
reproduces(
|
||||
None,
|
||||
|
||||
@@ -9,15 +9,15 @@
|
||||
<meta property="og:site_name" content="SolidCraft">
|
||||
<meta property="og:title" content="SolidCraft: try it in your browser">
|
||||
<meta property="og:description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
|
||||
<meta property="og:url" content="https://solidcraft.ai/">
|
||||
<meta property="og:image" content="https://docs.solidcraft.io/og.png">
|
||||
<meta property="og:url" content="https://bherbruck.github.io/solidcraft/app/">
|
||||
<meta property="og:image" content="https://bherbruck.github.io/solidcraft/og.png">
|
||||
<meta property="og:image:width" content="1280">
|
||||
<meta property="og:image:height" content="640">
|
||||
<meta property="og:image:alt" content="SolidCraft: open-source parametric CAD built in Rust">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="SolidCraft: try it in your browser">
|
||||
<meta name="twitter:description" content="Open-source parametric CAD built in Rust. Desktop, browser, and MCP for AI agents.">
|
||||
<meta name="twitter:image" content="https://docs.solidcraft.io/og.png">
|
||||
<meta name="twitter:image" content="https://bherbruck.github.io/solidcraft/og.png">
|
||||
<meta name="twitter:image:alt" content="SolidCraft: open-source parametric CAD built in Rust">
|
||||
<link data-trunk rel="rust" data-bin="solidcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<link data-trunk rel="copy-file" href="../../assets/fonts/biz-udp-gothic/BIZUDPGothic-Regular.ttf" data-target-path="fonts" />
|
||||
|
||||
@@ -27,9 +27,7 @@ mod web {
|
||||
|
||||
const CANVAS_ID: &str = "solidcraft_canvas";
|
||||
const LOADING_ID: &str = "solidcraft_loading";
|
||||
/// A 32-bit float depth buffer (no stencil): WebGPU and WebGL2 both have it, and the viewport
|
||||
/// draws it with reversed depth, whose precision follows the distance from the eye (#1434).
|
||||
const DEPTH_BITS: u8 = 32;
|
||||
const DEPTH_BITS: u8 = 24;
|
||||
|
||||
/// Seconds between autosaves of unsaved work.
|
||||
const AUTOSAVE_S: f64 = 30.0;
|
||||
@@ -481,7 +479,7 @@ mod web {
|
||||
let panel = files.clone();
|
||||
let services = Services {
|
||||
// Open shows the browser's files (and the computer's, from there).
|
||||
pick_open: Some(Box::new(move |_: &[&str]| {
|
||||
pick_open: Some(Box::new(move || {
|
||||
panel.panel.set(true);
|
||||
Box::pin(std::future::ready(None))
|
||||
})),
|
||||
|
||||
+10
-39
@@ -94,20 +94,10 @@ impl eframe::App for App {
|
||||
solidcraft_ui_egui::recovery_ui::close(&mut self.solve);
|
||||
solidcraft_engine::crash::end_session();
|
||||
// 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) {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
command.args(&args);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// Not tied to this process: its own process group, and no console (the PowerShell
|
||||
// that waits for an installer is hidden; the app itself is detached).
|
||||
let hidden_shell = program.file_stem().is_some_and(|n| n.eq_ignore_ascii_case("powershell"));
|
||||
command.creation_flags(0x0000_0200 | if hidden_shell { 0x0800_0000 } else { 0x0000_0008 });
|
||||
}
|
||||
if let Err(e) = command.spawn() {
|
||||
log::error!("update: starting {}: {e}", program.display());
|
||||
}
|
||||
if let Some((program, args)) = solidcraft_ui_egui::update::take_launch(&mut self.solve)
|
||||
&& let Err(e) = std::process::Command::new(&program).args(&args).spawn()
|
||||
{
|
||||
log::error!("update: starting {}: {e}", program.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,15 +107,9 @@ fn services(cc: &eframe::CreationContext<'_>) -> Services {
|
||||
let open_parent = parent.clone();
|
||||
let program_parent = parent.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |first: &[&str]| {
|
||||
// The file type the command reads comes first, so the picker opens on it (#1801).
|
||||
let mut dialog = open_parent.clone();
|
||||
if !first.is_empty() {
|
||||
let label = first.iter().map(|e| e.to_uppercase()).collect::<Vec<_>>().join(", ");
|
||||
let both: Vec<String> = first.iter().flat_map(|e| [e.to_lowercase(), e.to_uppercase()]).collect();
|
||||
dialog = dialog.add_filter(label, &both);
|
||||
}
|
||||
let future = dialog
|
||||
pick_open: Some(Box::new(move || {
|
||||
let future = open_parent
|
||||
.clone()
|
||||
.add_filter(
|
||||
"Designs, CAD files and meshes",
|
||||
&[
|
||||
@@ -422,10 +406,6 @@ fn msaa() -> u16 {
|
||||
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
|
||||
|
||||
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
|
||||
/// ([`startup::float_depth_everywhere`]); else [`DEPTH_BITS`]. Not in safe mode.
|
||||
const FLOAT_DEPTH_BITS: u8 = 32;
|
||||
/// The section cap marks where it shows in the stencil.
|
||||
const STENCIL_BITS: u8 = 8;
|
||||
const MSAA: u16 = 4;
|
||||
@@ -507,8 +487,6 @@ fn main() -> eframe::Result {
|
||||
notes.push("Safe mode: default settings (yours are kept for the next normal start), no recovery offer, software rendering.".into());
|
||||
}
|
||||
let samples = if safe_mode { MSAA } else { msaa() };
|
||||
let wgpu_options = wgpu_options(cpu_renderer, if safe_mode { None } else { backend_preference() }.as_deref());
|
||||
let depth_bits = if !safe_mode && startup::float_depth_everywhere(&wgpu_options) { FLOAT_DEPTH_BITS } else { DEPTH_BITS };
|
||||
// Crashes leave a report in the crash folder (solidcraft_engine::crash, docs/crash-reports.md).
|
||||
let crashed = solidcraft_engine::crash::default_dir()
|
||||
.map(|dir| {
|
||||
@@ -528,7 +506,7 @@ fn main() -> eframe::Result {
|
||||
solidcraft_engine::crash::phase("window");
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: app_viewport()?,
|
||||
depth_buffer: depth_bits,
|
||||
depth_buffer: DEPTH_BITS,
|
||||
stencil_buffer: STENCIL_BITS,
|
||||
multisampling: samples,
|
||||
// Kept with the other settings, not in a folder named after the app id. Safe mode reads
|
||||
@@ -541,7 +519,7 @@ fn main() -> eframe::Result {
|
||||
settings.as_ref().map(|d| d.join("app.ron"))
|
||||
},
|
||||
persist_window: !safe_mode,
|
||||
wgpu_options,
|
||||
wgpu_options: wgpu_options(cpu_renderer, if safe_mode { None } else { backend_preference() }.as_deref()),
|
||||
..Default::default()
|
||||
};
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
@@ -591,7 +569,7 @@ fn main() -> eframe::Result {
|
||||
if let Some(rs) = &cc.wgpu_render_state {
|
||||
eprintln!("SolidCraft graphics: {:?}, MSAA {}x (requested {}x)", rs.adapter.get_info().backend, rs.msaa_samples, samples);
|
||||
solidcraft_engine::crash::phase("viewport pipelines (shader compile)");
|
||||
app.set_wgpu(rs, depth_bits, STENCIL_BITS, rs.msaa_samples);
|
||||
app.set_wgpu(rs, DEPTH_BITS, STENCIL_BITS, rs.msaa_samples);
|
||||
solidcraft_ui_egui::gpu::install_picture_renderer(rs);
|
||||
// The graphics driver is loaded now; it may have put its own exception filter
|
||||
// in front of ours.
|
||||
@@ -697,13 +675,6 @@ fn wgpu_options(cpu: bool, preference: Option<&str>) -> eframe::egui_wgpu::WgpuC
|
||||
if cpu {
|
||||
setup.native_adapter_selector = Some(std::sync::Arc::new(startup::pick_cpu_adapter));
|
||||
}
|
||||
// A float depth buffer with a stencil, wherever the adapter has it (see `FLOAT_DEPTH_BITS`).
|
||||
let base = setup.device_descriptor.clone();
|
||||
setup.device_descriptor = std::sync::Arc::new(move |adapter| {
|
||||
let mut d = base(adapter);
|
||||
d.required_features |= adapter.features() & startup::FLOAT_DEPTH_STENCIL;
|
||||
d
|
||||
});
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
//! 3Dconnexion HID navigation on Windows (through hidapi) and Linux (through spacenavd when it
|
||||
//! runs, else hidraw). The device reader never touches the document or UI; it publishes the
|
||||
//! latest axes, and the egui thread applies them once per frame.
|
||||
//! 3Dconnexion HID navigation on Windows (through hidapi) and Linux (through hidraw). The device
|
||||
//! reader never touches the document or UI; it publishes the latest axes, and the egui thread
|
||||
//! applies them once per frame.
|
||||
|
||||
mod hid_descriptor;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod hidraw;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod spacenavd;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -158,21 +156,14 @@ struct Reading {
|
||||
axes: Axes,
|
||||
translation_at: Instant,
|
||||
rotation_at: Instant,
|
||||
/// The source says when the cap is back at rest, so a reading stays until the next one.
|
||||
/// A HID device repeats its report while the cap is held; spacenavd sends a record only when
|
||||
/// the values change, and a steady hold can go seconds without one.
|
||||
held: bool,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
fn new(now: Instant) -> Self {
|
||||
Self { axes: Axes::default(), translation_at: now, rotation_at: now, held: false }
|
||||
Self { axes: Axes::default(), translation_at: now, rotation_at: now }
|
||||
}
|
||||
|
||||
fn current(self, now: Instant) -> Axes {
|
||||
if self.held {
|
||||
return self.axes;
|
||||
}
|
||||
Axes {
|
||||
translation: if now.duration_since(self.translation_at) < STALE_AFTER { self.axes.translation } else { [0; 3] },
|
||||
rotation: if now.duration_since(self.rotation_at) < STALE_AFTER { self.axes.rotation } else { [0; 3] },
|
||||
@@ -235,15 +226,6 @@ fn publish(ctx: &Context, shared: &Mutex<Reading>, layout: Layout, report: &[u8]
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes the cap's position from spacenavd.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn publish_held(ctx: &Context, shared: &Mutex<Reading>, axes: Axes) {
|
||||
if let Ok(mut reading) = shared.lock() {
|
||||
*reading = Reading { axes, held: true, ..Reading::new(Instant::now()) };
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// The device is gone: stop reporting its last position.
|
||||
fn reset(ctx: &Context, shared: &Mutex<Reading>) {
|
||||
if let Ok(mut reading) = shared.lock() {
|
||||
@@ -294,21 +276,15 @@ fn device_layout(device: &hidapi::HidDevice) -> Layout {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the 3D mouse through spacenavd when it runs, so what `spnavcfg` sets (swapped and inverted
|
||||
/// axes, sensitivity, dead zones) applies here as in other programs. Without the daemon it reads
|
||||
/// `/dev/hidrawN` with plain blocking reads, which end with an error when the device is unplugged.
|
||||
/// Opening needs permission: most distributions grant it to the logged-in user for devices that
|
||||
/// carry the `uaccess` udev tag, which a rule for the 3D mouse has to add.
|
||||
/// Reads `/dev/hidrawN` with plain blocking reads, which end with an error when the device is
|
||||
/// unplugged. Opening needs permission: most distributions grant it to the logged-in user for
|
||||
/// devices that carry the `uaccess` udev tag, which a rule for the 3D mouse has to add.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn reader(ctx: Context, shared: Arc<Mutex<Reading>>) {
|
||||
use std::io::Read;
|
||||
let mut denied = None;
|
||||
loop {
|
||||
if let Some(daemon) = spacenavd::connect() {
|
||||
log::info!("3D mouse: reading spacenavd, which applies the spnavcfg settings");
|
||||
spacenavd::read(daemon, |axes| publish_held(&ctx, &shared, axes));
|
||||
reset(&ctx, &shared);
|
||||
} else if let Some(device) = hidraw::find() {
|
||||
if let Some(device) = hidraw::find() {
|
||||
match std::fs::File::open(&device.path) {
|
||||
Ok(mut file) => {
|
||||
denied = None;
|
||||
@@ -371,23 +347,16 @@ impl SpaceMouse {
|
||||
/// Before the app's own hook (which adds the control channel's events): with navigation on,
|
||||
/// the wheel events 3DxWare makes from the cap's motion are dropped.
|
||||
pub fn raw_input_hook(&mut self, enabled: bool, raw: &mut egui::RawInput) {
|
||||
self.raw_input_hook_at(enabled, raw, Instant::now());
|
||||
}
|
||||
|
||||
fn raw_input_hook_at(&mut self, enabled: bool, raw: &mut egui::RawInput, now: Instant) {
|
||||
if !enabled {
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
let moving = self.shared.lock().map(|reading| reading.current(now).moving()).unwrap_or(false);
|
||||
self.wheel.filter(moving, now.duration_since(self.started).as_secs_f64(), &mut raw.events);
|
||||
}
|
||||
|
||||
pub fn tick(&mut self, app: &mut SolveApp, ctx: &Context) {
|
||||
self.tick_at(app, ctx, Instant::now());
|
||||
}
|
||||
|
||||
/// The frame at `now`. Tests pass their own clock, so a slow runner can't age a reading.
|
||||
fn tick_at(&mut self, app: &mut SolveApp, ctx: &Context, now: Instant) {
|
||||
let now = Instant::now();
|
||||
let seconds = now.duration_since(self.last_frame).as_secs_f64();
|
||||
self.last_frame = now;
|
||||
if now.duration_since(self.mapping_checked_at) >= RETRY_AFTER {
|
||||
@@ -434,19 +403,6 @@ mod tests {
|
||||
assert_eq!(reading.current(later), Axes { translation: [1, 2, 3], rotation: [4, 5, 6] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_reading_stays_until_the_next_one_and_a_hid_reading_goes_stale() {
|
||||
let now = Instant::now();
|
||||
let axes = Axes { translation: [0, 200, 0], rotation: [0; 3] };
|
||||
let later = now + STALE_AFTER * 20;
|
||||
// spacenavd sends nothing while the values stay the same: the push lasts.
|
||||
let held = Reading { axes, held: true, ..Reading::new(now) };
|
||||
assert_eq!(held.current(later), axes);
|
||||
// A HID device repeats its report: silence means the cap, or the device, is gone.
|
||||
let hid = Reading { axes, ..Reading::new(now) };
|
||||
assert_eq!(hid.current(later), Axes::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combined_report_one_carries_translation_and_rotation_together() {
|
||||
let now = Instant::now();
|
||||
@@ -530,9 +486,6 @@ mod tests {
|
||||
#[test]
|
||||
fn each_frame_hands_the_view_its_motion_through_the_drivers_mapping() {
|
||||
// The reader's latest tilt, and a profile that makes tilt roll: the frame's motion rolls.
|
||||
// The frame runs at the reading's own time, so a slow runner can't let the reading go stale.
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
|
||||
app.home.open = false;
|
||||
let now = Instant::now();
|
||||
let mut reading = Reading::new(now);
|
||||
reading.axes.rotation = [0, 350, 0];
|
||||
@@ -544,7 +497,9 @@ mod tests {
|
||||
wheel: WheelGuard::default(),
|
||||
started: now,
|
||||
};
|
||||
mouse.tick_at(&mut app, &Context::default(), now);
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), solidcraft_ui_egui::Services::default());
|
||||
app.home.open = false;
|
||||
mouse.tick(&mut app, &Context::default());
|
||||
let DeviceMotion { motion, seconds } = app.viewport.device_motion.expect("the frame hands the page its motion");
|
||||
assert_eq!(motion, Motion { translation: [0.0; 3], rotation: [0.0, 0.0, -1.0] });
|
||||
assert!(seconds > 0.0);
|
||||
@@ -559,7 +514,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse(reading: Reading, now: Instant) -> SpaceMouse {
|
||||
fn mouse(reading: Reading) -> SpaceMouse {
|
||||
let now = Instant::now();
|
||||
SpaceMouse {
|
||||
shared: Arc::new(Mutex::new(reading)),
|
||||
last_frame: now,
|
||||
@@ -576,37 +532,36 @@ mod tests {
|
||||
let now = Instant::now();
|
||||
let mut tilted = Reading::new(now);
|
||||
tilted.axes.rotation = [-200, 0, 0];
|
||||
let mut moving = mouse(tilted, now);
|
||||
let mut moving = mouse(tilted);
|
||||
let mut raw = egui::RawInput { events: vec![wheel(), egui::Event::Zoom(1.1), egui::Event::Text("a".into())], ..Default::default() };
|
||||
moving.raw_input_hook_at(true, &mut raw, now);
|
||||
moving.raw_input_hook(true, &mut raw);
|
||||
assert_eq!(raw.events, [egui::Event::Text("a".into())]);
|
||||
// With navigation off, the wheel is the cap's only way to move the view: kept.
|
||||
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
|
||||
moving.raw_input_hook_at(false, &mut raw, now);
|
||||
moving.raw_input_hook(false, &mut raw);
|
||||
assert_eq!(raw.events.len(), 1);
|
||||
// The cap at rest: the wheel is the user's.
|
||||
let mut resting = mouse(Reading::new(now), now);
|
||||
let mut resting = mouse(Reading::new(now));
|
||||
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
|
||||
resting.raw_input_hook_at(true, &mut raw, now);
|
||||
resting.raw_input_hook(true, &mut raw);
|
||||
assert_eq!(raw.events.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wheel_is_the_users_again_once_the_cap_has_been_still_a_moment() {
|
||||
let now = Instant::now();
|
||||
let mut tilted = Reading::new(now);
|
||||
let mut tilted = Reading::new(Instant::now());
|
||||
tilted.axes.rotation = [-200, 0, 0];
|
||||
let mut cap = mouse(tilted, now);
|
||||
let mut cap = mouse(tilted);
|
||||
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
|
||||
cap.raw_input_hook_at(true, &mut raw, now);
|
||||
cap.raw_input_hook(true, &mut raw);
|
||||
assert!(raw.events.is_empty(), "dropped while the cap moves");
|
||||
// Let go, then wait out the quiet time.
|
||||
let later = now + Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60);
|
||||
if let Ok(mut reading) = cap.shared.lock() {
|
||||
*reading = Reading::new(later);
|
||||
*reading = Reading::new(Instant::now());
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs_f64(solidcraft_ui_egui::space_mouse::WHEEL_QUIET_S) + Duration::from_millis(60));
|
||||
let mut raw = egui::RawInput { events: vec![wheel()], ..Default::default() };
|
||||
cap.raw_input_hook_at(true, &mut raw, later);
|
||||
cap.raw_input_hook(true, &mut raw);
|
||||
assert_eq!(raw.events.len(), 1, "kept once the cap has been still");
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
//! Reading a 3D mouse through `spacenavd` on Linux. The daemon owns the device and applies what
|
||||
//! `spnavcfg` sets (swapped and inverted axes, sensitivity, dead zones) before it hands the motion
|
||||
//! to its clients, so a program that reads the HID device itself bypasses that setup. Over its
|
||||
//! socket the daemon sends fixed 32-byte records: eight native-endian `i32`, the first the kind of
|
||||
//! record (0 for motion, then x y z rx ry rz and the milliseconds since the last record).
|
||||
//! Other records (button presses, from newer daemons also configuration changes) are ignored.
|
||||
//!
|
||||
//! The socket is plain file I/O, so no library is needed, and it needs no udev rule: the daemon
|
||||
//! is what has access to the device.
|
||||
|
||||
use std::io::Read;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::Path;
|
||||
|
||||
use solidcraft_ui_egui::space_mouse::{Axes, FULL_SCALE};
|
||||
|
||||
/// Where the daemon listens. `/var/run` is a link to `/run` on current systems.
|
||||
const SOCKETS: [&str; 2] = ["/var/run/spnav.sock", "/run/spnav.sock"];
|
||||
|
||||
const RECORD_BYTES: usize = 32;
|
||||
|
||||
/// What the daemon reports at full deflection (seen with a SpaceMouse Compact and a default
|
||||
/// sensitivity). Our axes are in the raw HID units of [`FULL_SCALE`].
|
||||
const DAEMON_FULL_SCALE: i64 = 500;
|
||||
|
||||
pub fn connect() -> Option<UnixStream> {
|
||||
SOCKETS.iter().find_map(|path| connect_to(Path::new(path)))
|
||||
}
|
||||
|
||||
fn connect_to(path: &Path) -> Option<UnixStream> {
|
||||
UnixStream::connect(path).ok()
|
||||
}
|
||||
|
||||
/// The axes of one record, or `None` for a record that is not motion.
|
||||
///
|
||||
/// The daemon's frame is right-handed with x to the right, y away from the user and z up; ours is
|
||||
/// the device's raw one, x right, y towards the user and z down, so y and z (and the rotations
|
||||
/// about them) change sign. With nothing set in `spnavcfg` the two give the same motion; what
|
||||
/// the user swaps or inverts there then carries over.
|
||||
fn decode(record: &[u8; RECORD_BYTES]) -> Option<Axes> {
|
||||
let mut data = [0_i32; 8];
|
||||
for (slot, bytes) in data.iter_mut().zip(record.as_chunks::<4>().0) {
|
||||
*slot = i32::from_ne_bytes(*bytes);
|
||||
}
|
||||
let [kind, x, y, z, rx, ry, rz, _period] = data;
|
||||
(kind == 0).then(|| Axes {
|
||||
translation: [unit(x), unit(-i64::from(y)), unit(-i64::from(z))],
|
||||
rotation: [unit(rx), unit(-i64::from(ry)), unit(-i64::from(rz))],
|
||||
})
|
||||
}
|
||||
|
||||
/// A daemon value in our raw units. Out-of-range values stay in `i16`: they are input from another
|
||||
/// process.
|
||||
fn unit(value: impl Into<i64>) -> i16 {
|
||||
let scaled = value.into() * i64::from(FULL_SCALE) / DAEMON_FULL_SCALE;
|
||||
i16::try_from(scaled.clamp(i64::from(i16::MIN), i64::from(i16::MAX))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Hands every motion record to `publish` until the daemon closes the connection or fails. A
|
||||
/// partial record at the end is dropped.
|
||||
pub fn read(mut stream: impl Read, mut publish: impl FnMut(Axes)) {
|
||||
let mut record = [0_u8; RECORD_BYTES];
|
||||
loop {
|
||||
match stream.read_exact(&mut record) {
|
||||
Ok(()) => {
|
||||
if let Some(axes) = decode(&record) {
|
||||
publish(axes);
|
||||
}
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
Err(error) => {
|
||||
log::info!("3D mouse: spacenavd connection ended: {error}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
|
||||
fn record(data: [i32; 8]) -> [u8; RECORD_BYTES] {
|
||||
let mut bytes = [0_u8; RECORD_BYTES];
|
||||
for (chunk, value) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(data) {
|
||||
*chunk = value.to_ne_bytes();
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn motion_records_become_axes_in_the_devices_raw_frame() {
|
||||
// Full deflection of the daemon's x, y and z is the device's full scale, and y and z flip.
|
||||
assert_eq!(decode(&record([0, 500, 500, 500, 0, 0, 0, 8])), Some(Axes { translation: [350, -350, -350], rotation: [0; 3] }));
|
||||
// Rotations follow translations: right-handed in both frames, so ry and rz flip as y and z do.
|
||||
assert_eq!(decode(&record([0, 0, 0, 0, 250, 250, 250, 8])), Some(Axes { translation: [0; 3], rotation: [175, -175, -175] }));
|
||||
// Rest is a motion record of zeros.
|
||||
assert_eq!(decode(&record([0, 0, 0, 0, 0, 0, 0, 1200])), Some(Axes::default()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_spnavcfg_swaps_reaches_the_view() {
|
||||
// The daemon sends a push away as y. With Y and Z swapped in spnavcfg it sends the same push
|
||||
// as z, and the view gets a lift (raw z) instead of the zoom (raw y).
|
||||
let before = decode(&record([0, 0, 500, 0, 0, 0, 0, 8])).map(|axes| axes.translation);
|
||||
let after = decode(&record([0, 0, 0, 500, 0, 0, 0, 8])).map(|axes| axes.translation);
|
||||
assert_eq!(before, Some([0, -350, 0]));
|
||||
assert_eq!(after, Some([0, 0, -350]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_records_and_hostile_values_are_harmless() {
|
||||
// A button record (kind 1, press) and one of an unknown kind are not motion.
|
||||
assert_eq!(decode(&record([1, 0, 1, 0, 0, 0, 0, 0])), None);
|
||||
assert_eq!(decode(&record([7, 500, 500, 500, 500, 500, 500, 0])), None);
|
||||
// Nothing overflows on the extremes of `i32`.
|
||||
let extreme = decode(&record([0, i32::MIN, i32::MIN, i32::MAX, i32::MAX, i32::MIN, i32::MIN, -1]));
|
||||
assert_eq!(extreme.map(|axes| axes.translation[0]), Some(i16::MIN));
|
||||
assert_eq!(extreme.map(|axes| axes.translation[1]), Some(i16::MAX));
|
||||
assert_eq!(extreme.map(|axes| axes.rotation[0]), Some(i16::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_is_read_record_by_record_until_it_ends() {
|
||||
let (mut daemon, client) = UnixStream::pair().expect("a socket pair");
|
||||
let mut bytes = Vec::new();
|
||||
bytes.extend(record([0, 100, 0, 0, 0, 0, 0, 8]));
|
||||
bytes.extend(record([2, 1, 0, 0, 0, 0, 0, 0])); // a button release: skipped
|
||||
bytes.extend(record([0, 0, 0, 0, 0, 0, 0, 900]));
|
||||
bytes.extend([1, 2, 3]); // the daemon went away mid-record
|
||||
daemon.write_all(&bytes).expect("written");
|
||||
drop(daemon);
|
||||
let mut seen = Vec::new();
|
||||
read(client, |axes| seen.push(axes.translation));
|
||||
assert_eq!(seen, [[70, 0, 0], [0, 0, 0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_daemon_means_no_connection() {
|
||||
let missing = std::env::temp_dir().join(format!("sc-no-spnav-{}.sock", std::process::id()));
|
||||
assert!(connect_to(&missing).is_none());
|
||||
}
|
||||
}
|
||||
@@ -157,23 +157,6 @@ pub fn choose_backends(
|
||||
Some(WINDOWS_ORDER.into_iter().find(|b| has_hardware(*b)).unwrap_or(Backends::DX12))
|
||||
}
|
||||
|
||||
/// The device feature for a 32-bit float depth buffer with a stencil (reversed depth, #1434).
|
||||
pub const FLOAT_DEPTH_STENCIL: eframe::wgpu::Features = eframe::wgpu::Features::DEPTH32FLOAT_STENCIL8;
|
||||
|
||||
/// Whether every adapter `options` could start offers a float depth buffer with a stencil. eframe
|
||||
/// makes the window's depth buffer from the depth bits before it picks the adapter, so the window
|
||||
/// asks for a float one only when whichever it picks has it.
|
||||
pub fn float_depth_everywhere(options: &eframe::egui_wgpu::WgpuConfiguration) -> bool {
|
||||
let eframe::egui_wgpu::WgpuSetup::CreateNew(setup) = &options.wgpu_setup else { return false };
|
||||
let mut desc = eframe::wgpu::InstanceDescriptor::new_without_display_handle_from_env();
|
||||
desc.backends = setup.instance_descriptor.backends;
|
||||
let instance = eframe::wgpu::Instance::new(desc);
|
||||
let adapters = pollster::block_on(instance.enumerate_adapters(setup.instance_descriptor.backends));
|
||||
let all = !adapters.is_empty() && adapters.iter().all(|a| a.features().contains(FLOAT_DEPTH_STENCIL));
|
||||
log::info!("graphics: float depth with stencil on every adapter: {all}");
|
||||
all
|
||||
}
|
||||
|
||||
/// The order backends are tried in on Windows.
|
||||
pub const WINDOWS_ORDER: [eframe::wgpu::Backends; 3] = [eframe::wgpu::Backends::DX12, eframe::wgpu::Backends::VULKAN, eframe::wgpu::Backends::GL];
|
||||
|
||||
|
||||
@@ -1338,20 +1338,6 @@ pub(crate) fn paint_with(p: &Painter, r: Rect, name: &str, ink: Color32, fill: C
|
||||
pen.poly(&[(6.0, 10.0), (18.0, 10.0), (18.0, 15.0), (6.0, 15.0)], pen.fill, a);
|
||||
pen.arrow((21.0, 17.0), (21.0, 6.0), a);
|
||||
}
|
||||
"cam" => {
|
||||
// A cam on its shaft, its lobe up under the follower it lifts.
|
||||
let cam: Vec<(f32, f32)> = (0..36)
|
||||
.map(|k| {
|
||||
let t = std::f32::consts::TAU * k as f32 / 36.0;
|
||||
let r = 5.0 + 3.0 * (0.5 + 0.5 * t.sin()).powi(3);
|
||||
(11.0 + r * t.cos(), 16.0 - r * t.sin())
|
||||
})
|
||||
.collect();
|
||||
pen.poly(&cam, pen.fill, ink);
|
||||
pen.dot(11.0, 16.0, ink);
|
||||
pen.poly(&[(9.0, 2.0), (13.0, 2.0), (13.0, 8.0), (9.0, 8.0)], pen.fill, a);
|
||||
pen.arrow((18.5, 9.5), (18.5, 2.5), a);
|
||||
}
|
||||
"interference" => {
|
||||
pen.closed(&[(3.0, 5.0), (14.0, 5.0), (14.0, 16.0), (3.0, 16.0)], ink);
|
||||
pen.poly(&[(9.0, 10.0), (14.0, 10.0), (14.0, 16.0), (9.0, 16.0)], ic.interference, ic.interference);
|
||||
|
||||
@@ -4,21 +4,15 @@
|
||||
"2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Screenshot anhängen: kopieren und einfügen oder als PNG speichern und hochladen.",
|
||||
"3. Click Submit new issue on GitHub to send your report.": "3. Auf GitHub auf Submit new issue klicken, um den Bericht zu senden.",
|
||||
"AI": "KI",
|
||||
"Acceleration": "Beschleunigung",
|
||||
"Against": "Gegen",
|
||||
"Alignment": "Ausrichtung",
|
||||
"All components": "Alle Komponenten",
|
||||
"Arc length": "Bogenlänge",
|
||||
"Area": "Fläche",
|
||||
"BROWSER": "BROWSER",
|
||||
"Bends": "Biegungen",
|
||||
"Boundary": "Begrenzung",
|
||||
"Centre to centre": "Mitte zu Mitte",
|
||||
"Check collisions": "Kollisionen prüfen",
|
||||
"Circumference": "Umfang",
|
||||
"Collisions": "Kollisionen",
|
||||
"Construction": "Konstruktionslinie",
|
||||
"Contact sets": "Kontaktsätze",
|
||||
"Continuity": "Stetigkeit",
|
||||
"Copy Error Message": "Fehlermeldung kopieren",
|
||||
"Copy Warning Message": "Warnmeldung kopieren",
|
||||
@@ -28,10 +22,8 @@
|
||||
"Curvature (G2)": "Krümmung (G2)",
|
||||
"Do not export hidden edges": "Verdeckte Kanten nicht exportieren",
|
||||
"Drive Joint": "Gelenk antreiben",
|
||||
"Duration": "Dauer",
|
||||
"Edges": "Kanten",
|
||||
"Edit Profile Sketch": "Profile-Skizze bearbeiten",
|
||||
"Export Animation…": "Animation exportieren…",
|
||||
"Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren",
|
||||
"Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…",
|
||||
"Export DXF…": "DXF exportieren…",
|
||||
@@ -49,7 +41,6 @@
|
||||
"Max": "Max",
|
||||
"Min": "Min",
|
||||
"Mitre": "Gehrung",
|
||||
"New study": "Neue Untersuchung",
|
||||
"No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.",
|
||||
"None": "Keine",
|
||||
"Notch": "Ausklinkung",
|
||||
@@ -57,12 +48,9 @@
|
||||
"Overall length": "Gesamtlänge",
|
||||
"Pass through": "Durch Punkte",
|
||||
"Picked": "Ausgewählte",
|
||||
"Picked point": "Gewählter Punkt",
|
||||
"Plot": "Diagramm",
|
||||
"Position (G0)": "Position (G0)",
|
||||
"Profiles/Curves": "Profile/Kurven",
|
||||
"Projection": "Projektion",
|
||||
"Quantity": "Größe",
|
||||
"RULED SURFACE": "REGELFLÄCHE",
|
||||
"Rectangular": "Rechteckig",
|
||||
"Reference face": "Referenzfläche",
|
||||
@@ -71,7 +59,6 @@
|
||||
"Restore outer boundary": "Äußere Begrenzung wiederherstellen",
|
||||
"Revert Position": "Position zurücksetzen",
|
||||
"Round": "Rund",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Die Studie als animiertes GIF speichern, so wie der Ansichtsbereich sie zeigt",
|
||||
"Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)",
|
||||
"Selection filter": "Auswahlfilter",
|
||||
"Send your report on GitHub": "Bericht auf GitHub senden",
|
||||
@@ -81,7 +68,6 @@
|
||||
"Sketch geometry and profiles": "Skizzengeometrie und Profile",
|
||||
"Sketch points": "Skizzenpunkte",
|
||||
"Slot width": "Langlochbreite",
|
||||
"Study": "Untersuchung",
|
||||
"Tangent (G1)": "Tangente (G1)",
|
||||
"Tear": "Reißen",
|
||||
"Thickness Outside": "Dicke außen",
|
||||
@@ -90,7 +76,6 @@
|
||||
"Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.",
|
||||
"Type": "Typ",
|
||||
"UNTRIM": "TRIMMEN AUFHEBEN",
|
||||
"Velocity": "Geschwindigkeit",
|
||||
"Vertices": "Scheitelpunkte",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).",
|
||||
"Wall Location": "Wandlage",
|
||||
@@ -107,13 +92,6 @@
|
||||
"browser.precision": "Genauigkeit: {precision}",
|
||||
"browser.sketch_name": "Skizze {number}",
|
||||
"browser.units": "Einheiten: {units}",
|
||||
"cam.flat": "Flachstößel",
|
||||
"cam.follower": "Stößel",
|
||||
"cam.knife": "Schneide",
|
||||
"cam.needs_joints": "braucht ein Gelenk, das sich dreht, und eines, das gleitet oder schwenkt",
|
||||
"cam.roller": "Rolle",
|
||||
"cam.roller_pick": "Rolle (optional)",
|
||||
"cam.tip_pick": "Spitze (optional)",
|
||||
"cmd.appearance_assign": "Erscheinungsbild",
|
||||
"cmd.appearance_library": "Erscheinungsbild-Bibliothek",
|
||||
"cmd.appearance_list": "Erscheinungsbilder auflisten",
|
||||
@@ -217,7 +195,6 @@
|
||||
"cmd.inspect_minimum_radius": "Mindestradiusanalyse",
|
||||
"cmd.inspect_zebra": "Zebra-Analyse",
|
||||
"cmd.joint_as_built": "Fertigungsgelenk",
|
||||
"cmd.joint_cam": "Nocken",
|
||||
"cmd.joint_create": "Gelenk",
|
||||
"cmd.joint_delete": "Gelenk löschen",
|
||||
"cmd.joint_drive": "Gelenke antreiben",
|
||||
@@ -248,11 +225,8 @@
|
||||
"cmd.model_threads": "Gewinde auflisten",
|
||||
"cmd.motion_delete": "Bewegungsuntersuchung löschen",
|
||||
"cmd.motion_export": "Bewegungsuntersuchung exportieren",
|
||||
"cmd.motion_export_animation": "Bewegungsanimation exportieren",
|
||||
"cmd.motion_interference": "Kollisionen der Bewegungsuntersuchung",
|
||||
"cmd.motion_list": "Bewegungsuntersuchungen auflisten",
|
||||
"cmd.motion_play": "Bewegungsuntersuchung abspielen",
|
||||
"cmd.motion_plot": "Diagramm der Bewegungsuntersuchung",
|
||||
"cmd.motion_study": "Bewegungsuntersuchung",
|
||||
"cmd.motion_trace": "Bewegungsbahn",
|
||||
"cmd.motion_trace_keep": "Bewegungsbahn behalten",
|
||||
@@ -454,18 +428,6 @@
|
||||
"drive.stopped_by_contact": "Angehalten bei {value}: {a} würde {b} durchdringen",
|
||||
"drive.stopped_by_loop": "Angehalten bei {value}: die Schleife über {joint} lässt sich nicht weiter schließen",
|
||||
"drive.unconnected": "Bewegt nichts: {part} ist mit nichts Festgesetztem verbunden",
|
||||
"dxf.cancel_wait": "Warten, bis der Export angehalten wurde…",
|
||||
"dxf.cancelled": "DXF-Export abgebrochen",
|
||||
"dxf.cancelling": "DXF-Export wird abgebrochen",
|
||||
"dxf.exporting": "DXF wird exportiert",
|
||||
"dxf.invalid_tolerance": "Die Kurventoleranz muss zwischen 0,0001 und 1 mm liegen.",
|
||||
"dxf.progress.index": "Flächen vorbereiten (2/5)",
|
||||
"dxf.progress.meshes": "Netze vorbereiten (1/5)",
|
||||
"dxf.progress.occlusion": "Verdeckte Kanten ermitteln (4/5)",
|
||||
"dxf.progress.projection": "Geometrie projizieren (3/5)",
|
||||
"dxf.progress.write": "DXF schreiben (5/5)",
|
||||
"dxf.tolerance": "Kurventoleranz",
|
||||
"dxf.tolerance_help": "Nur sichtbare Körper. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.",
|
||||
"home.documentation": "Dokumentation",
|
||||
"home.in_this_browser": "in diesem Browser",
|
||||
"home.missing": "fehlt",
|
||||
@@ -494,10 +456,6 @@
|
||||
"joint.from_bodies_hint": "Jeder ausgewählte Körper kommt in eine eigene neue Komponente und bleibt, wo er ist.",
|
||||
"joint.one_body": "Beide Auswahlen liegen auf {body}. Wählen Sie die zweite auf einem anderen Teil.",
|
||||
"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.",
|
||||
"motion.checked_to": "Nur bis Schritt {step} geprüft: der Prüfaufwand ist erschöpft",
|
||||
"motion.collision": "{a} · {b}: Schritte {steps}",
|
||||
"motion.duration_hint": "Sekunden (leer: pro Schritt)",
|
||||
"motion.no_collisions": "Keine Kollisionen in der Untersuchung",
|
||||
"nav.touchpad.help": "Umschalt gedrückt halten und den Zeiger zum Verschieben bewegen; mit Alt/Option drehen. Keine Maustaste nötig. Vertikales Scrollen zoomt.",
|
||||
"nav.touchpad.label": "Touchpad",
|
||||
"nav.touchpad.orbit": "Drehen (Alt/Option halten und bewegen; ohne Maustaste)",
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
"A new configuration, a copy of the active one": "A new configuration, a copy of the active one",
|
||||
"AI": "AI",
|
||||
"About SolidCraft": "About SolidCraft",
|
||||
"Acceleration": "Acceleration",
|
||||
"Active": "Active",
|
||||
"Active rule": "Active rule",
|
||||
"Add": "Add",
|
||||
@@ -15,10 +14,8 @@
|
||||
"Add Mid Radius": "Add Mid Radius",
|
||||
"Add Row": "Add Row",
|
||||
"Add condition": "Add condition",
|
||||
"Against": "Against",
|
||||
"Alignment": "Alignment",
|
||||
"All Sketch Points": "All Sketch Points",
|
||||
"All components": "All components",
|
||||
"All open designs": "All open designs",
|
||||
"Allowed expressions, separated by semicolons": "Allowed expressions, separated by semicolons",
|
||||
"Also deletes": "Also deletes",
|
||||
@@ -60,7 +57,6 @@
|
||||
"Configuration rules": "Configuration rules",
|
||||
"Construction": "Construction",
|
||||
"Contact": "Contact",
|
||||
"Contact sets": "Contact sets",
|
||||
"Continuity": "Continuity",
|
||||
"Copy Error Message": "Copy Error Message",
|
||||
"Copy Warning Message": "Copy Warning Message",
|
||||
@@ -91,13 +87,11 @@
|
||||
"Double-click to rename": "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": "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",
|
||||
"Drive Joint": "Drive Joint",
|
||||
"Duration": "Duration",
|
||||
"Edges": "Edges",
|
||||
"Edit Profile Sketch": "Edit Profile Sketch",
|
||||
"Enable rule": "Enable rule",
|
||||
"Enabled": "Enabled",
|
||||
"Explode": "Explode",
|
||||
"Export Animation…": "Export Animation…",
|
||||
"Export Current View as DXF": "Export Current View as DXF",
|
||||
"Export Current View as DXF…": "Export Current View as DXF…",
|
||||
"Export DXF…": "Export DXF…",
|
||||
@@ -155,7 +149,6 @@
|
||||
"Move earlier": "Move earlier",
|
||||
"Move later": "Move later",
|
||||
"Name": "Name",
|
||||
"New study": "New study",
|
||||
"No crash reports.": "No crash reports.",
|
||||
"No matching appearances": "No matching appearances",
|
||||
"No visible bodies to export.": "No visible bodies to export.",
|
||||
@@ -174,10 +167,8 @@
|
||||
"Per Edge": "Per Edge",
|
||||
"Pick the tool bodies": "Pick the tool bodies",
|
||||
"Picked": "Picked",
|
||||
"Picked point": "Picked point",
|
||||
"Place at the origin instead": "Place at the origin instead",
|
||||
"Playback": "Playback",
|
||||
"Plot": "Plot",
|
||||
"Position": "Position",
|
||||
"Position (0 to 1)": "Position (0 to 1)",
|
||||
"Position (G0)": "Position (G0)",
|
||||
@@ -186,7 +177,6 @@
|
||||
"Preview leaves the current design unchanged.": "Preview leaves the current design unchanged.",
|
||||
"Profiles/Curves": "Profiles/Curves",
|
||||
"Projection": "Projection",
|
||||
"Quantity": "Quantity",
|
||||
"RECENT": "RECENT",
|
||||
"RULED SURFACE": "RULED SURFACE",
|
||||
"Radius Fit": "Radius Fit",
|
||||
@@ -221,7 +211,6 @@
|
||||
"Round": "Round",
|
||||
"Rule": "Rule",
|
||||
"Save Rule": "Save Rule",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Save the study as an animated GIF, seen as the viewport shows it",
|
||||
"Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.",
|
||||
"Scale factor": "Scale factor",
|
||||
"Search": "Search",
|
||||
@@ -252,7 +241,6 @@
|
||||
"Stand this part up?": "Stand this part up?",
|
||||
"Step": "Step",
|
||||
"Steps": "Steps",
|
||||
"Study": "Study",
|
||||
"Style": "Style",
|
||||
"Suppressed": "Suppressed",
|
||||
"Swap Ends": "Swap Ends",
|
||||
@@ -282,7 +270,6 @@
|
||||
"Use selected face as fixed plane": "Use selected face as fixed plane",
|
||||
"VIEW": "VIEW",
|
||||
"Value": "Value",
|
||||
"Velocity": "Velocity",
|
||||
"Vertices": "Vertices",
|
||||
"View navigator": "View navigator",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Visible bodies only. Curves use line segments (0.01 mm tolerance).",
|
||||
@@ -306,13 +293,6 @@
|
||||
"browser.precision": "Precision: {precision}",
|
||||
"browser.sketch_name": "Sketch{number}",
|
||||
"browser.units": "Units: {units}",
|
||||
"cam.flat": "Flat face",
|
||||
"cam.follower": "Follower",
|
||||
"cam.knife": "Knife edge",
|
||||
"cam.needs_joints": "needs a joint that turns and one that slides or swings",
|
||||
"cam.roller": "Roller",
|
||||
"cam.roller_pick": "Roller (optional)",
|
||||
"cam.tip_pick": "Tip (optional)",
|
||||
"cmd.appearance_assign": "Appearance",
|
||||
"cmd.appearance_library": "Appearance Library",
|
||||
"cmd.appearance_list": "List Appearances",
|
||||
@@ -416,7 +396,6 @@
|
||||
"cmd.inspect_minimum_radius": "Minimum Radius Analysis",
|
||||
"cmd.inspect_zebra": "Zebra Analysis",
|
||||
"cmd.joint_as_built": "As-Built Joint",
|
||||
"cmd.joint_cam": "Cam",
|
||||
"cmd.joint_create": "Joint",
|
||||
"cmd.joint_delete": "Delete Joint",
|
||||
"cmd.joint_drive": "Drive Joints",
|
||||
@@ -447,11 +426,8 @@
|
||||
"cmd.model_threads": "List Threads",
|
||||
"cmd.motion_delete": "Delete Motion Study",
|
||||
"cmd.motion_export": "Export Motion Study",
|
||||
"cmd.motion_export_animation": "Export Motion Animation",
|
||||
"cmd.motion_interference": "Motion Interference",
|
||||
"cmd.motion_list": "List Motion Studies",
|
||||
"cmd.motion_play": "Play Motion Study",
|
||||
"cmd.motion_plot": "Plot Motion Study",
|
||||
"cmd.motion_study": "Motion Study",
|
||||
"cmd.motion_trace": "Motion Trace",
|
||||
"cmd.motion_trace_keep": "Keep Motion Trace",
|
||||
@@ -655,18 +631,6 @@
|
||||
"drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}",
|
||||
"drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further",
|
||||
"drive.unconnected": "Moves nothing: {part} is not connected to anything grounded",
|
||||
"dxf.cancel_wait": "Waiting for the export to stop…",
|
||||
"dxf.cancelled": "DXF export cancelled",
|
||||
"dxf.cancelling": "Cancelling DXF export",
|
||||
"dxf.exporting": "Exporting DXF",
|
||||
"dxf.invalid_tolerance": "Curve tolerance must be between 0.0001 and 1 mm.",
|
||||
"dxf.progress.index": "Preparing surfaces (2/5)",
|
||||
"dxf.progress.meshes": "Preparing meshes (1/5)",
|
||||
"dxf.progress.occlusion": "Resolving hidden lines (4/5)",
|
||||
"dxf.progress.projection": "Projecting geometry (3/5)",
|
||||
"dxf.progress.write": "Writing DXF (5/5)",
|
||||
"dxf.tolerance": "Curve tolerance",
|
||||
"dxf.tolerance_help": "Visible bodies only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.",
|
||||
"expression, e.g. 25 mm": "expression, e.g. 25 mm",
|
||||
"fits the face, e.g. M8": "fits the face, e.g. M8",
|
||||
"from the rule": "from the rule",
|
||||
@@ -698,10 +662,6 @@
|
||||
"joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.",
|
||||
"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.",
|
||||
"motion.checked_to": "Checked to step {step} only: the check ran out of its work budget",
|
||||
"motion.collision": "{a} · {b}: steps {steps}",
|
||||
"motion.duration_hint": "seconds (empty: per step)",
|
||||
"motion.no_collisions": "No collisions over the study",
|
||||
"nav.touchpad.help": "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.",
|
||||
"nav.touchpad.label": "Touchpad",
|
||||
"nav.touchpad.orbit": "Orbit (hold Alt/Option and move; no mouse button)",
|
||||
@@ -800,10 +760,6 @@
|
||||
"sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve",
|
||||
"sketch_text.use_font_file": "Use the font file {path}",
|
||||
"the parts library is not available": "the parts library is not available",
|
||||
"thread.automatic_size": "Automatic size",
|
||||
"thread.designation": "Designation",
|
||||
"thread.iso_metric": "ISO metric",
|
||||
"thread.select_size": "Select size",
|
||||
"timeline.group": "New Feature Folder",
|
||||
"timeline.move_many": "Move Timeline Items",
|
||||
"timeline.move_to_group": "Move Features to Folder",
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
"3. Click Submit new issue on GitHub to send your report.": "3. Cliquer sur Submit new issue sur GitHub pour envoyer votre rapport.",
|
||||
"A new configuration, a copy of the active one": "Nouvelle configuration, copie de la configuration active",
|
||||
"About SolidCraft": "À propos de SolidCraft",
|
||||
"Acceleration": "Accélération",
|
||||
"Active": "Actif",
|
||||
"Active rule": "Règle active",
|
||||
"Add": "Ajouter",
|
||||
@@ -14,10 +13,8 @@
|
||||
"Add Mid Radius": "Ajouter un rayon intermédiaire",
|
||||
"Add Row": "Ajouter une ligne",
|
||||
"Add condition": "Ajouter une condition",
|
||||
"Against": "Contre",
|
||||
"Alignment": "Alignement",
|
||||
"All Sketch Points": "Tous les points d'esquisse",
|
||||
"All components": "Tous les composants",
|
||||
"All open designs": "Toutes les conceptions ouvertes",
|
||||
"Allowed expressions, separated by semicolons": "Expressions autorisées, séparées par des points-virgules",
|
||||
"Also deletes": "Supprime aussi",
|
||||
@@ -56,7 +53,6 @@
|
||||
"Configuration rules": "Règles de configuration",
|
||||
"Construction": "Construction",
|
||||
"Contact": "Contact",
|
||||
"Contact sets": "Jeux de contact",
|
||||
"Continuity": "Continuité",
|
||||
"Copy Error Message": "Copier le message d'erreur",
|
||||
"Copy Warning Message": "Copier le message d'avertissement",
|
||||
@@ -84,13 +80,11 @@
|
||||
"Double-click to rename": "Double-cliquer pour renommer",
|
||||
"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": "Double-clic sur le bouton du milieu dans la vue : Accueil (vue d'accueil, cadrant ce qui est affiché), Cadrer (cadrer ce qui est affiché en gardant l'orientation) ou rien",
|
||||
"Drive Joint": "Piloter la liaison",
|
||||
"Duration": "Durée",
|
||||
"Edges": "Arêtes",
|
||||
"Edit Profile Sketch": "Modifier l'esquisse du profil",
|
||||
"Enable rule": "Activer la règle",
|
||||
"Enabled": "Activé",
|
||||
"Explode": "Éclater",
|
||||
"Export Animation…": "Exporter l'animation…",
|
||||
"Extents": "Étendues",
|
||||
"Face": "Face",
|
||||
"Face attachment lost": "Rattachement à la face perdu",
|
||||
@@ -141,7 +135,6 @@
|
||||
"Move earlier": "Déplacer plus tôt",
|
||||
"Move later": "Déplacer plus tard",
|
||||
"Name": "Nom",
|
||||
"New study": "Nouvelle étude",
|
||||
"No crash reports.": "Aucun rapport de plantage.",
|
||||
"No matching appearances": "Aucune apparence correspondante",
|
||||
"None": "Aucun",
|
||||
@@ -158,10 +151,8 @@
|
||||
"Per Edge": "Par arête",
|
||||
"Pick the tool bodies": "Choisir les corps outils",
|
||||
"Picked": "Sélectionnés",
|
||||
"Picked point": "Point choisi",
|
||||
"Place at the origin instead": "Placer plutôt à l'origine",
|
||||
"Playback": "Lecture",
|
||||
"Plot": "Graphique",
|
||||
"Position": "Position",
|
||||
"Position (0 to 1)": "Position (0 à 1)",
|
||||
"Position (G0)": "Position (G0)",
|
||||
@@ -169,7 +160,6 @@
|
||||
"Preview Row": "Aperçu de la ligne",
|
||||
"Preview leaves the current design unchanged.": "L'aperçu ne modifie pas la conception actuelle.",
|
||||
"Profiles/Curves": "Profils/Courbes",
|
||||
"Quantity": "Grandeur",
|
||||
"RECENT": "RÉCENTS",
|
||||
"RULED SURFACE": "SURFACE RÉGLÉE",
|
||||
"Radius Fit": "Ajustement du rayon",
|
||||
@@ -204,7 +194,6 @@
|
||||
"Round": "Arrondi",
|
||||
"Rule": "Règle",
|
||||
"Save Rule": "Enregistrer la règle",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Enregistrer l'étude en GIF animé, telle que la fenêtre d'affichage la montre",
|
||||
"Saved preview. Geometry is being checked before editing.": "Aperçu enregistré. La géométrie est en cours de vérification avant modification.",
|
||||
"Scale factor": "Facteur d'échelle",
|
||||
"Search": "Rechercher",
|
||||
@@ -234,7 +223,6 @@
|
||||
"Stand this part up?": "Redresser cette pièce ?",
|
||||
"Step": "Étape",
|
||||
"Steps": "Étapes",
|
||||
"Study": "Étude",
|
||||
"Style": "Style",
|
||||
"Suppressed": "Désactivé",
|
||||
"Swap Ends": "Permuter les extrémités",
|
||||
@@ -263,7 +251,6 @@
|
||||
"Use selected face as fixed plane": "Utiliser la face sélectionnée comme plan fixe",
|
||||
"VIEW": "VUE",
|
||||
"Value": "Valeur",
|
||||
"Velocity": "Vitesse",
|
||||
"Vertices": "Sommets",
|
||||
"View navigator": "Repère de navigation",
|
||||
"Volume": "Volume",
|
||||
@@ -286,13 +273,6 @@
|
||||
"browser.precision": "Précision : {precision}",
|
||||
"browser.sketch_name": "Esquisse{number}",
|
||||
"browser.units": "Unités : {units}",
|
||||
"cam.flat": "Plateau",
|
||||
"cam.follower": "Suiveur",
|
||||
"cam.knife": "Arête",
|
||||
"cam.needs_joints": "nécessite une liaison qui tourne et une qui glisse ou pivote",
|
||||
"cam.roller": "Galet",
|
||||
"cam.roller_pick": "Galet (facultatif)",
|
||||
"cam.tip_pick": "Pointe (facultatif)",
|
||||
"cmd.appearance_assign": "Apparence",
|
||||
"cmd.appearance_library": "Bibliothèque d'apparences",
|
||||
"cmd.appearance_list": "Lister les apparences",
|
||||
@@ -396,7 +376,6 @@
|
||||
"cmd.inspect_minimum_radius": "Analyse du rayon minimal",
|
||||
"cmd.inspect_zebra": "Analyse zébrée",
|
||||
"cmd.joint_as_built": "Liaison telle que construite",
|
||||
"cmd.joint_cam": "Came",
|
||||
"cmd.joint_create": "Liaison",
|
||||
"cmd.joint_delete": "Supprimer la liaison",
|
||||
"cmd.joint_drive": "Piloter les liaisons",
|
||||
@@ -427,11 +406,8 @@
|
||||
"cmd.model_threads": "Lister les filetages",
|
||||
"cmd.motion_delete": "Supprimer l'étude de mouvement",
|
||||
"cmd.motion_export": "Exporter l'étude de mouvement",
|
||||
"cmd.motion_export_animation": "Exporter l'animation du mouvement",
|
||||
"cmd.motion_interference": "Collisions de l'étude de mouvement",
|
||||
"cmd.motion_list": "Lister les études de mouvement",
|
||||
"cmd.motion_play": "Lire l'étude de mouvement",
|
||||
"cmd.motion_plot": "Graphique de l'étude de mouvement",
|
||||
"cmd.motion_study": "Étude de mouvement",
|
||||
"cmd.motion_trace": "Trajectoire de mouvement",
|
||||
"cmd.motion_trace_keep": "Conserver la trajectoire de mouvement",
|
||||
@@ -664,10 +640,6 @@
|
||||
"joint.from_bodies_hint": "Chaque corps sélectionné passe dans un nouveau composant à lui et reste où il est.",
|
||||
"joint.one_body": "Les deux sélections sont sur {body}. Choisissez la seconde sur une autre pièce.",
|
||||
"joint.one_component": "Ces pièces sont des corps d'un même composant : {bodies}. Une liaison déplace un composant par rapport à un autre, chaque pièce a donc besoin de son propre composant.",
|
||||
"motion.checked_to": "Vérifié jusqu'à l'étape {step} seulement : la vérification a épuisé son budget de calcul",
|
||||
"motion.collision": "{a} · {b} : étapes {steps}",
|
||||
"motion.duration_hint": "secondes (vide : par étape)",
|
||||
"motion.no_collisions": "Aucune collision au cours de l'étude",
|
||||
"nav.touchpad.help": "Maintenir Maj et déplacer le pointeur pour faire un panoramique ; maintenir Alt/Option et le déplacer pour orbiter. Aucun bouton de souris n'est nécessaire. Le défilement vertical zoome.",
|
||||
"nav.touchpad.label": "Pavé tactile",
|
||||
"nav.touchpad.orbit": "Orbite (maintenir Alt/Option et déplacer ; sans bouton de souris)",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,6 @@
|
||||
"A new configuration, a copy of the active one": "アクティブな構成をコピーして新しい構成を作成",
|
||||
"AI": "AI",
|
||||
"About SolidCraft": "SolidCraft について",
|
||||
"Acceleration": "加速度",
|
||||
"Active": "アクティブ",
|
||||
"Active rule": "有効なルール",
|
||||
"Add": "追加",
|
||||
@@ -15,10 +14,8 @@
|
||||
"Add Mid Radius": "中間半径を追加",
|
||||
"Add Row": "行を追加",
|
||||
"Add condition": "条件を追加",
|
||||
"Against": "相手",
|
||||
"Alignment": "配置",
|
||||
"All Sketch Points": "すべてのスケッチ点",
|
||||
"All components": "すべてのコンポーネント",
|
||||
"All open designs": "すべての開いているデザイン",
|
||||
"Allowed expressions, separated by semicolons": "使用可能な式(セミコロンで区切る)",
|
||||
"Also deletes": "同時に削除される要素:",
|
||||
@@ -60,7 +57,6 @@
|
||||
"Configuration rules": "構成ルール",
|
||||
"Construction": "コンストラクション",
|
||||
"Contact": "接触",
|
||||
"Contact sets": "接触セット",
|
||||
"Continuity": "連続性",
|
||||
"Copy Error Message": "エラーメッセージをコピー",
|
||||
"Copy Warning Message": "警告メッセージをコピー",
|
||||
@@ -91,13 +87,11 @@
|
||||
"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": "ビュー上で中ボタンをダブルクリックした時の動作: ホーム(全体を収めたホームビュー)、全体表示(向きを維持して全体を収める)、または無効",
|
||||
"Drive Joint": "ジョイントを駆動",
|
||||
"Duration": "時間",
|
||||
"Edges": "エッジ",
|
||||
"Edit Profile Sketch": "プロファイルスケッチを編集",
|
||||
"Enable rule": "ルールを有効化",
|
||||
"Enabled": "有効",
|
||||
"Explode": "分解",
|
||||
"Export Animation…": "アニメーションをエクスポート…",
|
||||
"Export Current View as DXF": "現在の表示をDXFでエクスポート",
|
||||
"Export Current View as DXF…": "現在の表示をDXFでエクスポート…",
|
||||
"Export DXF…": "DXFをエクスポート…",
|
||||
@@ -155,7 +149,6 @@
|
||||
"Move earlier": "前へ移動",
|
||||
"Move later": "後へ移動",
|
||||
"Name": "名前",
|
||||
"New study": "新規スタディ",
|
||||
"No crash reports.": "クラッシュレポートはありません。",
|
||||
"No matching appearances": "一致する外観がありません",
|
||||
"No visible bodies to export.": "出力する表示中のボディがありません。",
|
||||
@@ -174,10 +167,8 @@
|
||||
"Per Edge": "エッジごと",
|
||||
"Pick the tool bodies": "ツールボディを選択",
|
||||
"Picked": "選択したもの",
|
||||
"Picked point": "選択した点",
|
||||
"Place at the origin instead": "代わりに原点に配置",
|
||||
"Playback": "再生",
|
||||
"Plot": "グラフ",
|
||||
"Position": "位置",
|
||||
"Position (0 to 1)": "位置 (0〜1)",
|
||||
"Position (G0)": "位置 (G0)",
|
||||
@@ -186,7 +177,6 @@
|
||||
"Preview leaves the current design unchanged.": "プレビューは現在のデザインを変更しません。",
|
||||
"Profiles/Curves": "プロファイル/曲線",
|
||||
"Projection": "投影",
|
||||
"Quantity": "量",
|
||||
"RECENT": "最近使用した項目",
|
||||
"RULED SURFACE": "ルールドサーフェス",
|
||||
"Radius Fit": "半径フィット",
|
||||
@@ -221,7 +211,6 @@
|
||||
"Round": "丸め",
|
||||
"Rule": "ルール",
|
||||
"Save Rule": "ルールを保存",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "ビューポートの表示どおりにスタディをアニメーション GIF として保存",
|
||||
"Saved preview. Geometry is being checked before editing.": "保存済みのプレビューです。編集前にジオメトリを検証しています。",
|
||||
"Scale factor": "尺度係数",
|
||||
"Search": "検索",
|
||||
@@ -252,7 +241,6 @@
|
||||
"Stand this part up?": "このパーツを正立させますか?",
|
||||
"Step": "ステップ",
|
||||
"Steps": "ステップ数",
|
||||
"Study": "スタディ",
|
||||
"Style": "スタイル",
|
||||
"Suppressed": "抑制",
|
||||
"Swap Ends": "端点を入れ替え",
|
||||
@@ -282,7 +270,6 @@
|
||||
"Use selected face as fixed plane": "選択した面を固定平面として使用",
|
||||
"VIEW": "表示",
|
||||
"Value": "値",
|
||||
"Velocity": "速度",
|
||||
"Vertices": "頂点",
|
||||
"View navigator": "ビューナビゲーター",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "表示中のボディを出力します。曲線は線分で近似します(許容誤差0.01 mm)。",
|
||||
@@ -306,13 +293,6 @@
|
||||
"browser.precision": "精度: {precision}",
|
||||
"browser.sketch_name": "スケッチ{number}",
|
||||
"browser.units": "単位: {units}",
|
||||
"cam.flat": "平面",
|
||||
"cam.follower": "従動節",
|
||||
"cam.knife": "ナイフエッジ",
|
||||
"cam.needs_joints": "回転するジョイントと、スライドまたは揺動するジョイントが必要",
|
||||
"cam.roller": "ローラー",
|
||||
"cam.roller_pick": "ローラー (オプション)",
|
||||
"cam.tip_pick": "先端 (オプション)",
|
||||
"cmd.appearance_assign": "外観",
|
||||
"cmd.appearance_library": "外観ライブラリ",
|
||||
"cmd.appearance_list": "外観を一覧表示",
|
||||
@@ -416,7 +396,6 @@
|
||||
"cmd.inspect_minimum_radius": "最小半径解析",
|
||||
"cmd.inspect_zebra": "ゼブラ解析",
|
||||
"cmd.joint_as_built": "現位置ジョイント",
|
||||
"cmd.joint_cam": "カム",
|
||||
"cmd.joint_create": "ジョイント",
|
||||
"cmd.joint_delete": "ジョイントを削除",
|
||||
"cmd.joint_drive": "ジョイントを駆動",
|
||||
@@ -447,11 +426,8 @@
|
||||
"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_keep": "モーション トレースを保持",
|
||||
@@ -655,18 +631,6 @@
|
||||
"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": "表示中のボディを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。",
|
||||
"expression, e.g. 25 mm": "計算式 (例: 25 mm)",
|
||||
"fits the face, e.g. M8": "面に適合するサイズ (例: M8)",
|
||||
"from the rule": "ルールから",
|
||||
@@ -698,10 +662,6 @@
|
||||
"joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。",
|
||||
"joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。",
|
||||
"joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。",
|
||||
"motion.checked_to": "ステップ {step} までしか確認していません: 確認の計算量の上限に達しました",
|
||||
"motion.collision": "{a} · {b}: ステップ {steps}",
|
||||
"motion.duration_hint": "秒 (空欄: ステップごと)",
|
||||
"motion.no_collisions": "スタディ全体で衝突はありません",
|
||||
"nav.touchpad.help": "Shift を押しながらポインターを動かすとパン、Alt/Option を押しながら動かすと回転します。マウスボタンは不要です。縦スクロールでズームします。",
|
||||
"nav.touchpad.label": "タッチパッド",
|
||||
"nav.touchpad.orbit": "回転(Alt/Option を押しながら移動、マウスボタン不要)",
|
||||
@@ -800,10 +760,6 @@
|
||||
"sketch_text.path_hint": "文字が沿うスケッチの曲線: ここをクリックしてから曲線をクリック",
|
||||
"sketch_text.use_font_file": "フォント ファイル {path} を使用",
|
||||
"the parts library is not available": "パーツライブラリは利用できません",
|
||||
"thread.automatic_size": "サイズを自動選択",
|
||||
"thread.designation": "ねじの呼び",
|
||||
"thread.iso_metric": "ISOメートルねじ",
|
||||
"thread.select_size": "サイズを選択",
|
||||
"timeline.group": "フィーチャーフォルダを新規作成",
|
||||
"timeline.move_many": "タイムライン項目を移動",
|
||||
"timeline.move_to_group": "フィーチャーをフォルダへ移動",
|
||||
|
||||
@@ -4,21 +4,15 @@
|
||||
"2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. 스크린샷을 첨부하세요. 복사하여 붙여넣거나 PNG로 저장한 뒤 업로드하세요.",
|
||||
"3. Click Submit new issue on GitHub to send your report.": "3. GitHub에서 Submit new issue를 클릭하여 보고서를 보내세요.",
|
||||
"AI": "AI",
|
||||
"Acceleration": "가속도",
|
||||
"Against": "상대",
|
||||
"Alignment": "정렬",
|
||||
"All components": "모든 구성요소",
|
||||
"Arc length": "호 길이",
|
||||
"Area": "면적",
|
||||
"BROWSER": "브라우저",
|
||||
"Bends": "벤딩",
|
||||
"Boundary": "경계",
|
||||
"Centre to centre": "중심 간",
|
||||
"Check collisions": "충돌 확인",
|
||||
"Circumference": "원주",
|
||||
"Collisions": "충돌",
|
||||
"Construction": "구성선",
|
||||
"Contact sets": "접촉 집합",
|
||||
"Continuity": "연속성",
|
||||
"Copy Error Message": "오류 메시지 복사",
|
||||
"Copy Warning Message": "경고 메시지 복사",
|
||||
@@ -28,10 +22,8 @@
|
||||
"Curvature (G2)": "곡률 (G2)",
|
||||
"Do not export hidden edges": "숨겨진 모서리 내보내지 않기",
|
||||
"Drive Joint": "조인트 구동",
|
||||
"Duration": "지속 시간",
|
||||
"Edges": "모서리",
|
||||
"Edit Profile Sketch": "윤곽 스케치 편집",
|
||||
"Export Animation…": "애니메이션 내보내기…",
|
||||
"Export Current View as DXF": "현재 뷰를 DXF로 내보내기",
|
||||
"Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…",
|
||||
"Export DXF…": "DXF 내보내기…",
|
||||
@@ -49,7 +41,6 @@
|
||||
"Max": "최대",
|
||||
"Min": "최소",
|
||||
"Mitre": "연귀",
|
||||
"New study": "새 연구",
|
||||
"No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.",
|
||||
"None": "없음",
|
||||
"Notch": "노치",
|
||||
@@ -57,12 +48,9 @@
|
||||
"Overall length": "전체 길이",
|
||||
"Pass through": "통과점",
|
||||
"Picked": "선택한 항목",
|
||||
"Picked point": "선택한 점",
|
||||
"Plot": "그래프",
|
||||
"Position (G0)": "위치 (G0)",
|
||||
"Profiles/Curves": "프로파일/곡선",
|
||||
"Projection": "투영",
|
||||
"Quantity": "양",
|
||||
"RULED SURFACE": "룰드 서피스",
|
||||
"Rectangular": "직사각형",
|
||||
"Reference face": "참조 면",
|
||||
@@ -71,7 +59,6 @@
|
||||
"Restore outer boundary": "외부 경계 복원",
|
||||
"Revert Position": "위치 복원",
|
||||
"Round": "둥글게",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "뷰포트에 보이는 대로 스터디를 애니메이션 GIF로 저장",
|
||||
"Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)",
|
||||
"Selection filter": "선택 필터",
|
||||
"Send your report on GitHub": "GitHub에서 보고서 보내기",
|
||||
@@ -81,7 +68,6 @@
|
||||
"Sketch geometry and profiles": "스케치 기하 및 프로파일",
|
||||
"Sketch points": "스케치 점",
|
||||
"Slot width": "슬롯 폭",
|
||||
"Study": "연구",
|
||||
"Tangent (G1)": "접선 (G1)",
|
||||
"Tear": "찢김",
|
||||
"Thickness Outside": "바깥쪽 두께",
|
||||
@@ -90,7 +76,6 @@
|
||||
"Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.",
|
||||
"Type": "유형",
|
||||
"UNTRIM": "트림 해제",
|
||||
"Velocity": "속도",
|
||||
"Vertices": "꼭짓점",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).",
|
||||
"Wall Location": "벽 위치",
|
||||
@@ -107,13 +92,6 @@
|
||||
"browser.precision": "정밀도: {precision}",
|
||||
"browser.sketch_name": "스케치{number}",
|
||||
"browser.units": "단위: {units}",
|
||||
"cam.flat": "평면",
|
||||
"cam.follower": "종동절",
|
||||
"cam.knife": "나이프 에지",
|
||||
"cam.needs_joints": "회전하는 관절과 미끄러지거나 흔들리는 관절이 필요함",
|
||||
"cam.roller": "롤러",
|
||||
"cam.roller_pick": "롤러 (선택 사항)",
|
||||
"cam.tip_pick": "끝점 (선택 사항)",
|
||||
"cmd.appearance_assign": "외관",
|
||||
"cmd.appearance_library": "외관 라이브러리",
|
||||
"cmd.appearance_list": "외관 목록",
|
||||
@@ -217,7 +195,6 @@
|
||||
"cmd.inspect_minimum_radius": "최소 반경 분석",
|
||||
"cmd.inspect_zebra": "얼룩말줄무늬 분석",
|
||||
"cmd.joint_as_built": "조립 상태 관절",
|
||||
"cmd.joint_cam": "캠",
|
||||
"cmd.joint_create": "관절",
|
||||
"cmd.joint_delete": "관절 삭제",
|
||||
"cmd.joint_drive": "관절 구동",
|
||||
@@ -248,11 +225,8 @@
|
||||
"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_keep": "모션 궤적 유지",
|
||||
@@ -454,18 +428,6 @@
|
||||
"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": "표시된 바디만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.",
|
||||
"home.documentation": "문서",
|
||||
"home.in_this_browser": "이 브라우저에 저장됨",
|
||||
"home.missing": "찾을 수 없음",
|
||||
@@ -494,10 +456,6 @@
|
||||
"joint.from_bodies_hint": "선택한 각 바디가 제자리에 그대로 있으면서 자체의 새 구성 요소로 옮겨집니다.",
|
||||
"joint.one_body": "두 선택이 모두 {body}에 있습니다. 두 번째는 다른 부품에서 선택하세요.",
|
||||
"joint.one_component": "이 부품들은 한 구성 요소의 바디입니다: {bodies}. 관절은 한 구성 요소를 다른 구성 요소에 대해 움직이므로 부품마다 자체 구성 요소가 필요합니다.",
|
||||
"motion.checked_to": "{step} 단계까지만 확인했습니다: 확인 작업량 한도에 도달했습니다",
|
||||
"motion.collision": "{a} · {b}: {steps} 단계",
|
||||
"motion.duration_hint": "초 (비우면: 단계당)",
|
||||
"motion.no_collisions": "연구 전체에서 충돌이 없습니다",
|
||||
"nav.touchpad.help": "Shift를 누른 채 포인터를 움직이면 화면이 이동하고, Alt/Option을 누른 채 움직이면 회전합니다. 마우스 버튼은 필요 없습니다. 세로 스크롤로 확대/축소합니다.",
|
||||
"nav.touchpad.label": "터치패드",
|
||||
"nav.touchpad.orbit": "회전 (Alt/Option을 누르고 이동, 마우스 버튼 불필요)",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,6 @@
|
||||
"0 turns it off": "0 отключает",
|
||||
"A new configuration, a copy of the active one": "Новая конфигурация — копия активной",
|
||||
"About SolidCraft": "О SolidCraft",
|
||||
"Acceleration": "Ускорение",
|
||||
"Active": "Активный",
|
||||
"Active rule": "Активное правило",
|
||||
"Add": "Добавить",
|
||||
@@ -10,10 +9,8 @@
|
||||
"Add Mid Radius": "Добавить средний радиус",
|
||||
"Add Row": "Добавить строку",
|
||||
"Add condition": "Добавить условие",
|
||||
"Against": "Против",
|
||||
"Alignment": "Выравнивание",
|
||||
"All Sketch Points": "Все точки эскиза",
|
||||
"All components": "Все компоненты",
|
||||
"All open designs": "Все открытые дизайны",
|
||||
"Allowed expressions, separated by semicolons": "Разрешённые выражения через точку с запятой",
|
||||
"Also deletes": "Также удаляет",
|
||||
@@ -52,7 +49,6 @@
|
||||
"Configuration rules": "Правила конфигурации",
|
||||
"Construction": "Вспомогательная",
|
||||
"Contact": "Контакт",
|
||||
"Contact sets": "Наборы контактов",
|
||||
"Continuity": "Непрерывность",
|
||||
"Copy Error Message": "Скопировать сообщение об ошибке",
|
||||
"Copy Warning Message": "Скопировать предупреждение",
|
||||
@@ -80,13 +76,11 @@
|
||||
"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": "Двойной щелчок средней кнопкой в виде: «Главная» (главный вид, кадрирует показанное), «Вписать» (кадрирует, сохраняя ориентацию) или ничего",
|
||||
"Drive Joint": "Привод сопряжения",
|
||||
"Duration": "Длительность",
|
||||
"Edges": "Рёбра",
|
||||
"Edit Profile Sketch": "Редактировать эскиз профиля",
|
||||
"Enable rule": "Включить правило",
|
||||
"Enabled": "Включено",
|
||||
"Explode": "Разобрать",
|
||||
"Export Animation…": "Экспортировать анимацию…",
|
||||
"Extents": "Пределы",
|
||||
"Face attachment lost": "Привязка к грани потеряна",
|
||||
"Faces": "Грани",
|
||||
@@ -131,7 +125,6 @@
|
||||
"Move earlier": "Сдвинуть раньше",
|
||||
"Move later": "Сдвинуть позже",
|
||||
"Name": "Имя",
|
||||
"New study": "Новое исследование",
|
||||
"No crash reports.": "Нет отчётов о сбоях.",
|
||||
"No matching appearances": "Нет подходящих внешних видов",
|
||||
"Not available yet": "Пока недоступно",
|
||||
@@ -145,17 +138,14 @@
|
||||
"Path": "Траектория",
|
||||
"Per Edge": "По каждому ребру",
|
||||
"Pick the tool bodies": "Выберите тела-инструменты",
|
||||
"Picked point": "Выбранная точка",
|
||||
"Place at the origin instead": "Разместить в начале координат",
|
||||
"Playback": "Воспроизведение",
|
||||
"Plot": "График",
|
||||
"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 — конец",
|
||||
"Preview Row": "Строка предпросмотра",
|
||||
"Preview leaves the current design unchanged.": "Предпросмотр не меняет текущий дизайн.",
|
||||
"Quantity": "Величина",
|
||||
"RECENT": "НЕДАВНИЕ",
|
||||
"Radius Fit": "Подобрать радиус",
|
||||
"Ratio": "Отношение",
|
||||
@@ -187,7 +177,6 @@
|
||||
"Round": "Круглая",
|
||||
"Rule": "Правило",
|
||||
"Save Rule": "Сохранить правило",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Сохранить исследование как анимированный GIF, как его показывает видовой экран",
|
||||
"Saved preview. Geometry is being checked before editing.": "Сохранённый предпросмотр. Геометрия проверяется перед редактированием.",
|
||||
"Scale factor": "Коэффициент масштаба",
|
||||
"Search": "Поиск",
|
||||
@@ -216,7 +205,6 @@
|
||||
"Stand this part up?": "Поставить эту деталь вертикально?",
|
||||
"Step": "Шаг",
|
||||
"Steps": "Шаги",
|
||||
"Study": "Исследование",
|
||||
"Style": "Стиль",
|
||||
"Suppressed": "Подавлено",
|
||||
"Swap Ends": "Поменять концы",
|
||||
@@ -241,7 +229,6 @@
|
||||
"Use selected face as fixed plane": "Использовать выбранную грань как фиксированную плоскость",
|
||||
"VIEW": "ВИД",
|
||||
"Value": "Значение",
|
||||
"Velocity": "Скорость",
|
||||
"Vertices": "Вершины",
|
||||
"View navigator": "Навигатор видов",
|
||||
"Volume": "Объём",
|
||||
@@ -262,13 +249,6 @@
|
||||
"browser.precision": "Точность: {precision}",
|
||||
"browser.sketch_name": "Эскиз{number}",
|
||||
"browser.units": "Единицы: {units}",
|
||||
"cam.flat": "Плоский",
|
||||
"cam.follower": "Толкатель",
|
||||
"cam.knife": "Острие",
|
||||
"cam.needs_joints": "нужны вращающееся и скользящее или качающееся сопряжения",
|
||||
"cam.roller": "Ролик",
|
||||
"cam.roller_pick": "Ролик (необязательно)",
|
||||
"cam.tip_pick": "Острие (необязательно)",
|
||||
"cmd.appearance_assign": "Внешний вид",
|
||||
"cmd.appearance_library": "Библиотека внешних видов",
|
||||
"cmd.appearance_list": "Список внешних видов",
|
||||
@@ -372,7 +352,6 @@
|
||||
"cmd.inspect_minimum_radius": "Анализ минимального радиуса",
|
||||
"cmd.inspect_zebra": "Зебра-анализ",
|
||||
"cmd.joint_as_built": "Сопряжение на месте",
|
||||
"cmd.joint_cam": "Кулачок",
|
||||
"cmd.joint_create": "Сопряжение",
|
||||
"cmd.joint_delete": "Удалить сопряжение",
|
||||
"cmd.joint_drive": "Привод сопряжений",
|
||||
@@ -399,11 +378,8 @@
|
||||
"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_keep": "Сохранить траекторию движения",
|
||||
@@ -632,10 +608,6 @@
|
||||
"joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте.",
|
||||
"joint.one_body": "Оба выбора на {body}. Выберите второй на другой детали.",
|
||||
"joint.one_component": "Эти детали - тела одного компонента: {bodies}. Сопряжение двигает один компонент относительно другого, поэтому каждой детали нужен свой компонент.",
|
||||
"motion.checked_to": "Проверено только до шага {step}: проверка исчерпала свой бюджет работы",
|
||||
"motion.collision": "{a} · {b}: шаги {steps}",
|
||||
"motion.duration_hint": "секунды (пусто: на шаг)",
|
||||
"motion.no_collisions": "За всё исследование столкновений нет",
|
||||
"needs two joints": "нужны два сопряжения",
|
||||
"new configuration": "новая конфигурация",
|
||||
"new name": "новое имя",
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
"A new configuration, a copy of the active one": "Etkin konfigürasyonun kopyası olan yeni bir konfigürasyon",
|
||||
"AI": "AI",
|
||||
"About SolidCraft": "SolidCraft hakkında",
|
||||
"Acceleration": "İvme",
|
||||
"Active": "Etkin",
|
||||
"Active rule": "Etkin kural",
|
||||
"Add": "Ekle",
|
||||
@@ -15,10 +14,8 @@
|
||||
"Add Mid Radius": "Ara yarıçap ekle",
|
||||
"Add Row": "Satır ekle",
|
||||
"Add condition": "Koşul ekle",
|
||||
"Against": "Karşı",
|
||||
"Alignment": "Hizalama",
|
||||
"All Sketch Points": "Tüm eskiz noktaları",
|
||||
"All components": "Tüm bileşenler",
|
||||
"All open designs": "Tüm açık tasarımlar",
|
||||
"Allowed expressions, separated by semicolons": "Noktalı virgülle ayrılmış izin verilen ifadeler",
|
||||
"Also deletes": "Bunları da siler",
|
||||
@@ -59,7 +56,6 @@
|
||||
"Configuration rules": "Konfigürasyon kuralları",
|
||||
"Construction": "Yapı çizgisi",
|
||||
"Contact": "Temas",
|
||||
"Contact sets": "Temas kümeleri",
|
||||
"Copy Error Message": "Hata mesajını kopyala",
|
||||
"Copy Warning Message": "Uyarı mesajını kopyala",
|
||||
"Copy all licences": "Tüm lisansları kopyala",
|
||||
@@ -84,13 +80,11 @@
|
||||
"Double-click to rename": "Yeniden adlandırmak için çift tıklayın",
|
||||
"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": "Görünümde orta tuşla çift tıklama: Başlangıç (gösterileni çerçeveleyen başlangıç görünümü), Sığdır (yönü koruyarak gösterileni çerçeveler) veya hiçbir şey",
|
||||
"Drive Joint": "Bağlantıyı tahrik et",
|
||||
"Duration": "Süre",
|
||||
"Edges": "Kenarlar",
|
||||
"Edit Profile Sketch": "Profil eskizini düzenle",
|
||||
"Enable rule": "Kuralı etkinleştir",
|
||||
"Enabled": "Etkin",
|
||||
"Explode": "Patlat",
|
||||
"Export Animation…": "Animasyonu dışa aktar…",
|
||||
"Extents": "Kapsamlar",
|
||||
"Face": "Yüz",
|
||||
"Face attachment lost": "Yüze bağlama kayboldu",
|
||||
@@ -143,7 +137,6 @@
|
||||
"Move earlier": "Öne al",
|
||||
"Move later": "Sonraya al",
|
||||
"Name": "Ad",
|
||||
"New study": "Yeni etüt",
|
||||
"No crash reports.": "Çökme raporu yok.",
|
||||
"No matching appearances": "Eşleşen görünüm yok",
|
||||
"None": "Hiçbiri",
|
||||
@@ -159,17 +152,14 @@
|
||||
"Per Edge": "Kenar başına",
|
||||
"Pick the tool bodies": "Araç gövdelerini seçin",
|
||||
"Picked": "Seçilenler",
|
||||
"Picked point": "Seçilen nokta",
|
||||
"Place at the origin instead": "Bunun yerine orijine yerleştir",
|
||||
"Playback": "Oynatma",
|
||||
"Plot": "Grafik",
|
||||
"Position": "Konum",
|
||||
"Position (0 to 1)": "Konum (0 ile 1 arası)",
|
||||
"Position along the edge, 0 at the start end, 1 at the other": "Kenar boyunca konum: başlangıç ucunda 0, diğer uçta 1",
|
||||
"Preview Row": "Satırı önizle",
|
||||
"Preview leaves the current design unchanged.": "Önizleme geçerli tasarımı değiştirmez.",
|
||||
"Profiles/Curves": "Profiller/Eğriler",
|
||||
"Quantity": "Büyüklük",
|
||||
"RECENT": "SON KULLANILANLAR",
|
||||
"RULED SURFACE": "REGLE YÜZEY",
|
||||
"Radius Fit": "Yarıçap uydurma",
|
||||
@@ -203,7 +193,6 @@
|
||||
"Round": "Yuvarlak",
|
||||
"Rule": "Kural",
|
||||
"Save Rule": "Kuralı kaydet",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Etüdü görünüm alanında göründüğü gibi animasyonlu GIF olarak kaydet",
|
||||
"Saved preview. Geometry is being checked before editing.": "Kaydedilmiş önizleme. Düzenlemeden önce geometri kontrol ediliyor.",
|
||||
"Scale factor": "Ölçek faktörü",
|
||||
"Search": "Ara",
|
||||
@@ -234,7 +223,6 @@
|
||||
"Stand this part up?": "Bu parça dik çevrilsin mi?",
|
||||
"Step": "Adım",
|
||||
"Steps": "Adımlar",
|
||||
"Study": "Etüt",
|
||||
"Style": "Stil",
|
||||
"Suppressed": "Bastırılmış",
|
||||
"Swap Ends": "Uçları değiştir",
|
||||
@@ -261,7 +249,6 @@
|
||||
"Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan",
|
||||
"VIEW": "GÖRÜNÜM",
|
||||
"Value": "Değer",
|
||||
"Velocity": "Hız",
|
||||
"Vertices": "Köşe noktaları",
|
||||
"View navigator": "Görünüm gezgini",
|
||||
"Volume": "Hacim",
|
||||
@@ -413,11 +400,8 @@
|
||||
"cmd.model_threads": "Dişleri listele",
|
||||
"cmd.motion_delete": "Hareket etüdünü sil",
|
||||
"cmd.motion_export": "Hareket etüdünü dışa aktar",
|
||||
"cmd.motion_export_animation": "Hareket animasyonunu dışa aktar",
|
||||
"cmd.motion_interference": "Hareket etüdü çarpışmaları",
|
||||
"cmd.motion_list": "Hareket etütlerini listele",
|
||||
"cmd.motion_play": "Hareket etüdünü oynat",
|
||||
"cmd.motion_plot": "Hareket etüdü grafiği",
|
||||
"cmd.motion_study": "Hareket etüdü",
|
||||
"cmd.occurrence_copy": "Yapıştır (örnek)",
|
||||
"cmd.occurrence_ground": "Sabitle",
|
||||
@@ -631,10 +615,6 @@
|
||||
"joint.from_bodies_hint": "Seçilen her gövde kendi yeni bileşenine konur ve bulunduğu yerde kalır.",
|
||||
"joint.one_body": "Her iki seçim de {body} üzerinde. İkincisini başka bir parçada seçin.",
|
||||
"joint.one_component": "Bu parçalar tek bir bileşenin gövdeleridir: {bodies}. Bir bağlantı bir bileşeni diğerine göre hareket ettirir, bu nedenle her parçanın kendi bileşeni olması gerekir.",
|
||||
"motion.checked_to": "Yalnızca {step}. adıma kadar denetlendi: denetim iş bütçesini tüketti",
|
||||
"motion.collision": "{a} · {b}: adımlar {steps}",
|
||||
"motion.duration_hint": "saniye (boş: adım başına)",
|
||||
"motion.no_collisions": "Etüt boyunca çarpışma yok",
|
||||
"nav.touchpad.help": "Kaydırmak için Shift tuşunu basılı tutun ve imleci hareket ettirin; Alt/Option ile döndürün. Fare tuşu gerekmez. Dikey kaydırma yakınlaştırır.",
|
||||
"nav.touchpad.label": "Dokunmatik yüzey",
|
||||
"nav.touchpad.orbit": "Döndür (Alt/Option tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)",
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
"2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Додайте знімок екрана: скопіюйте й вставте його або збережіть і завантажте PNG.",
|
||||
"3. Click Submit new issue on GitHub to send your report.": "3. Натисніть Submit new issue на GitHub, щоб надіслати звіт.",
|
||||
"A new configuration, a copy of the active one": "Нова конфігурація, копія активної",
|
||||
"AI": "ШІ",
|
||||
"About SolidCraft": "Про SolidCraft",
|
||||
"Acceleration": "Прискорення",
|
||||
"Active": "Активна",
|
||||
"Active rule": "Активне правило",
|
||||
"Add": "Додати",
|
||||
@@ -15,10 +13,8 @@
|
||||
"Add Mid Radius": "Додати середній радіус",
|
||||
"Add Row": "Додати рядок",
|
||||
"Add condition": "Додати умову",
|
||||
"Against": "Проти",
|
||||
"Alignment": "Вирівнювання",
|
||||
"All Sketch Points": "Усі точки ескізу",
|
||||
"All components": "Усі компоненти",
|
||||
"All open designs": "Усі відкриті проєкти",
|
||||
"Allowed expressions, separated by semicolons": "Дозволені вирази, розділені крапками з комою",
|
||||
"Also deletes": "Також видаляє",
|
||||
@@ -28,7 +24,6 @@
|
||||
"Applied Radius": "Застосований радіус",
|
||||
"Apply To": "Застосувати до",
|
||||
"Apply to selection": "Застосувати до виділення",
|
||||
"Arc length": "Довжина дуги",
|
||||
"Area": "Площа",
|
||||
"Attachment": "Прив'язка",
|
||||
"BROWSER": "БРАУЗЕР",
|
||||
@@ -46,12 +41,10 @@
|
||||
"Center X": "Центр X",
|
||||
"Center Y": "Центр Y",
|
||||
"Center of mass": "Центр мас",
|
||||
"Centre to centre": "Від центра до центра",
|
||||
"Chamfer Type": "Тип фаски",
|
||||
"Check collisions": "Перевіряти зіткнення",
|
||||
"Checked": "Перевірено",
|
||||
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Виберіть нову площину. Геометрія та розміри ескізу залишаються незмінними у своїх двовимірних координатах.",
|
||||
"Circumference": "Довжина кола",
|
||||
"Close draft": "Закрити чернетку",
|
||||
"Collisions": "Зіткнення",
|
||||
"Colour": "Колір",
|
||||
@@ -60,10 +53,7 @@
|
||||
"Configuration rules": "Правила конфігурації",
|
||||
"Construction": "Конструкційна",
|
||||
"Contact": "Контакт",
|
||||
"Contact sets": "Набори контактів",
|
||||
"Continuity": "Неперервність",
|
||||
"Copy Error Message": "Копіювати повідомлення про помилку",
|
||||
"Copy Warning Message": "Копіювати попереджувальне повідомлення",
|
||||
"Copy all licences": "Копіювати всі ліцензії",
|
||||
"Copy diagnostic information": "Копіювати діагностичну інформацію",
|
||||
"Copy report": "Копіювати звіт",
|
||||
@@ -74,8 +64,6 @@
|
||||
"Countersink angle": "Кут зенкування",
|
||||
"Create Issue — review draft": "Створити повідомлення про проблему — перегляд чернетки",
|
||||
"Cube": "Куб",
|
||||
"Current orthographic view (1:1 mm)": "Поточний ортографічний вид (1:1 mm)",
|
||||
"Current perspective view": "Поточний перспективний вид",
|
||||
"Curvature (G2)": "Кривина (G2)",
|
||||
"Customize Toolbar": "Налаштувати панель інструментів",
|
||||
"Delete all": "Видалити все",
|
||||
@@ -87,23 +75,15 @@
|
||||
"Designs you open or save appear here.": "Проєкти, які ви відкриваєте чи зберігаєте, з'являються тут.",
|
||||
"Determined by To Object. Choose Angle to edit the angular extent.": "Визначається об'єктом призначення. Виберіть «Кут», щоб редагувати кутову протяжність.",
|
||||
"Discard": "Відхилити",
|
||||
"Do not export hidden edges": "Не експортувати приховані ребра",
|
||||
"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": "Подвійне клацання середньою кнопкою у виді: головний (головний вид, що охоплює показане), вписування (охопити показане, зберігаючи орієнтацію) або нічого",
|
||||
"Drive Joint": "Керувати з'єднанням",
|
||||
"Duration": "Тривалість",
|
||||
"Edges": "Ребра",
|
||||
"Edit Profile Sketch": "Редагувати ескіз профілю",
|
||||
"Enable rule": "Увімкнути правило",
|
||||
"Enabled": "Увімкнено",
|
||||
"Explode": "Рознести",
|
||||
"Export Animation…": "Експортувати анімацію…",
|
||||
"Export Current View as DXF": "Експортувати поточний вид як DXF",
|
||||
"Export Current View as DXF…": "Експортувати поточний вид як DXF…",
|
||||
"Export DXF…": "Експорт DXF…",
|
||||
"Export hidden edges as dashed lines": "Експортувати приховані ребра як штрихові лінії",
|
||||
"Extents": "Межі",
|
||||
"Face": "Грань",
|
||||
"Face attachment lost": "Втрачено прив'язку до грані",
|
||||
"Faces": "Грані",
|
||||
"Faces / edges / vertices": "Грані / ребра / вершини",
|
||||
@@ -120,12 +100,8 @@
|
||||
"Gap": "Проміжок",
|
||||
"Grid": "Сітка",
|
||||
"Height": "Висота",
|
||||
"Hidden edges": "Приховані ребра",
|
||||
"Holes": "Отвори",
|
||||
"Holes (edges on them)": "Отвори (ребра на них)",
|
||||
"Home view": "Головний вид",
|
||||
"In This Design": "У цьому проєкті",
|
||||
"In place (surfaces)": "На місці (поверхні)",
|
||||
"Inside": "Усередину",
|
||||
"Interferes": "Перетинається",
|
||||
"Issue title": "Заголовок повідомлення",
|
||||
@@ -143,11 +119,8 @@
|
||||
"Margin": "Відступ",
|
||||
"Mass": "Маса",
|
||||
"Material": "Матеріал",
|
||||
"Max": "Макс.",
|
||||
"Mid Radius": "Середній радіус",
|
||||
"Middle double-click": "Подвійне клацання середньою кнопкою",
|
||||
"Min": "Мін.",
|
||||
"Mitre": "Скіс",
|
||||
"Modeled": "Змодельовано",
|
||||
"More toolbar panels": "Більше панелей інструментів",
|
||||
"Motion": "Рух",
|
||||
@@ -155,11 +128,8 @@
|
||||
"Move earlier": "Перемістити раніше",
|
||||
"Move later": "Перемістити пізніше",
|
||||
"Name": "Назва",
|
||||
"New study": "Нове дослідження",
|
||||
"No crash reports.": "Немає звітів про збої.",
|
||||
"No matching appearances": "Немає відповідних виглядів",
|
||||
"No visible bodies to export.": "Немає видимих тіл для експорту.",
|
||||
"None": "Немає",
|
||||
"Not available yet": "Ще недоступно",
|
||||
"Notch": "Виріз",
|
||||
"Opacity": "Непрозорість",
|
||||
@@ -167,17 +137,13 @@
|
||||
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Параметричний 3D-CAD з відкритим вихідним кодом на Rust. Ліцензовано за MIT OR Apache-2.0.",
|
||||
"Other side": "Інший бік",
|
||||
"Outside": "Назовні",
|
||||
"Overall length": "Загальна довжина",
|
||||
"Parameter values": "Значення параметрів",
|
||||
"Pass through": "Через точки",
|
||||
"Path": "Траєкторія",
|
||||
"Per Edge": "На кожне ребро",
|
||||
"Pick the tool bodies": "Виберіть тіла інструмента",
|
||||
"Picked": "Вибрано",
|
||||
"Picked point": "Вибрана точка",
|
||||
"Place at the origin instead": "Натомість розмістити в початку координат",
|
||||
"Playback": "Відтворення",
|
||||
"Plot": "Графік",
|
||||
"Position": "Положення",
|
||||
"Position (0 to 1)": "Положення (від 0 до 1)",
|
||||
"Position (G0)": "Положення (G0)",
|
||||
@@ -185,17 +151,13 @@
|
||||
"Preview Row": "Рядок перегляду",
|
||||
"Preview leaves the current design unchanged.": "Попередній перегляд не змінює поточний проєкт.",
|
||||
"Profiles/Curves": "Профілі/криві",
|
||||
"Projection": "Проєкція",
|
||||
"Quantity": "Величина",
|
||||
"RECENT": "НЕДАВНІ",
|
||||
"RULED SURFACE": "ЛІНІЙЧАСТА ПОВЕРХНЯ",
|
||||
"Radius Fit": "Підгонка за радіусом",
|
||||
"Ratio": "Співвідношення",
|
||||
"Reattach selected face": "Повторно приєднати вибрану грань",
|
||||
"Recover": "Відновити",
|
||||
"Recover unsaved design?": "Відновити незбережений проєкт?",
|
||||
"Rectangular": "Прямокутний",
|
||||
"Reference face": "Опорна грань",
|
||||
"Remove Tools": "Прибрати інструменти",
|
||||
"Remove from list": "Прибрати зі списку",
|
||||
"Remove override": "Прибрати перевизначення",
|
||||
@@ -206,7 +168,6 @@
|
||||
"Remove this point": "Прибрати цю точку",
|
||||
"Report a bug — review a screenshot and open a GitHub draft": "Повідомити про помилку — переглянути знімок екрана й відкрити чернетку GitHub",
|
||||
"Reset Toolbar": "Скинути панель інструментів",
|
||||
"Restore outer boundary": "Відновити зовнішню межу",
|
||||
"Restore the inherited component or physical material appearance": "Відновити успадкований вигляд компонента або фізичного матеріалу",
|
||||
"Result": "Результат",
|
||||
"Retake screenshot": "Повторити знімок екрана",
|
||||
@@ -221,7 +182,6 @@
|
||||
"Round": "Круглий",
|
||||
"Rule": "Правило",
|
||||
"Save Rule": "Зберегти правило",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "Зберегти дослідження як анімований GIF, як його показує вікно перегляду",
|
||||
"Saved preview. Geometry is being checked before editing.": "Збережений перегляд. Геометрію перевіряють перед редагуванням.",
|
||||
"Scale factor": "Коефіцієнт масштабу",
|
||||
"Search": "Пошук",
|
||||
@@ -244,7 +204,6 @@
|
||||
"Sketch geometry and profiles": "Геометрія та профілі ескізу",
|
||||
"Sketch plane has no body-face attachment.": "Площина ескізу не має прив'язки до грані тіла.",
|
||||
"Sketch points": "Точки ескізу",
|
||||
"Slot width": "Ширина паза",
|
||||
"SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft закрився до того, як ці проєкти було збережено. Можна відкрити їхнє останнє автозбереження.",
|
||||
"Speed": "Швидкість",
|
||||
"Stand it up": "Вирівняти",
|
||||
@@ -252,7 +211,6 @@
|
||||
"Stand this part up?": "Вирівняти цю деталь?",
|
||||
"Step": "Крок",
|
||||
"Steps": "Кроки",
|
||||
"Study": "Дослідження",
|
||||
"Style": "Стиль",
|
||||
"Suppressed": "Придушено",
|
||||
"Swap Ends": "Поміняти кінці місцями",
|
||||
@@ -272,9 +230,7 @@
|
||||
"This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "Ця грань не може забезпечити надійну прив'язку. Виберіть іншу грань або явно використайте фіксовану площину.",
|
||||
"To Offset": "До зсуву",
|
||||
"Tolerance": "Допуск",
|
||||
"Turn off section analysis before exporting the view.": "Вимкніть аналіз перерізу перед експортом виду.",
|
||||
"Type": "Тип",
|
||||
"UNTRIM": "ЗНЯТИ ОБРІЗАННЯ",
|
||||
"Updating the preview": "Оновлення попереднього перегляду",
|
||||
"Use active author placement": "Використати активне вихідне розміщення",
|
||||
"Use fixed plane": "Використати фіксовану площину",
|
||||
@@ -282,10 +238,8 @@
|
||||
"Use selected face as fixed plane": "Використати вибрану грань як фіксовану площину",
|
||||
"VIEW": "ВИД",
|
||||
"Value": "Значення",
|
||||
"Velocity": "Швидкість",
|
||||
"Vertices": "Вершини",
|
||||
"View navigator": "Навігатор виду",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Лише видимі тіла. Криві подаються відрізками (допуск 0,01 mm).",
|
||||
"Volume": "Об'єм",
|
||||
"Wall": "Стінка",
|
||||
"Wall Location": "Розташування стінки",
|
||||
@@ -294,25 +248,12 @@
|
||||
"Width": "Ширина",
|
||||
"Will fail": "Зазнає невдачі",
|
||||
"angle, height": "кут, висота",
|
||||
"appearance.dielectric_ior": "Діелектричний IOR",
|
||||
"appearance.metallic": "Металевість",
|
||||
"appearance.pbr_help": "Перегляньте цю поверхню в режимі рендерингу або як PNG-зображення виробу. Без заломлення чи пропускання.",
|
||||
"appearance.pbr_opaque": "Непрозорий PBR",
|
||||
"appearance.roughness": "Шорсткість",
|
||||
"appearance.surface_response": "Відгук поверхні",
|
||||
"browser.body_name": "Тіло{number}",
|
||||
"browser.component_name": "Компонент{number}",
|
||||
"browser.parameters": "Параметри ({count})",
|
||||
"browser.precision": "Точність: {precision}",
|
||||
"browser.sketch_name": "Ескіз{number}",
|
||||
"browser.units": "Одиниці: {units}",
|
||||
"cam.flat": "Плоский",
|
||||
"cam.follower": "Штовхач",
|
||||
"cam.knife": "Вістря",
|
||||
"cam.needs_joints": "потрібні обертове й ковзне або хитне з'єднання",
|
||||
"cam.roller": "Ролик",
|
||||
"cam.roller_pick": "Ролик (необов'язково)",
|
||||
"cam.tip_pick": "Вістря (необов'язково)",
|
||||
"cmd.appearance_assign": "Вигляд",
|
||||
"cmd.appearance_library": "Бібліотека виглядів",
|
||||
"cmd.appearance_list": "Список виглядів",
|
||||
@@ -385,9 +326,6 @@
|
||||
"cmd.doc_recovery_discard": "Відхилити відновлений проєкт",
|
||||
"cmd.doc_recovery_list": "Проєкти для відновлення",
|
||||
"cmd.document_inspect": "Перевірити проєкт",
|
||||
"cmd.document_metadata": "Властивості проєкту",
|
||||
"cmd.document_metadata_remove": "Видалити властивість проєкту",
|
||||
"cmd.document_metadata_set": "Змінити властивості проєкту",
|
||||
"cmd.document_units": "Змінити одиниці проєкту",
|
||||
"cmd.edit_checkpoint": "Контрольна точка",
|
||||
"cmd.edit_restore_checkpoint": "Відновити контрольну точку",
|
||||
@@ -402,7 +340,6 @@
|
||||
"cmd.file_insert_mesh": "Вставити сітку",
|
||||
"cmd.file_insert_step": "Вставити STEP",
|
||||
"cmd.file_save_mesh": "Зберегти як сітку",
|
||||
"cmd.file_slicers": "Встановлені слайсери",
|
||||
"cmd.inspect_accessibility": "Аналіз доступності",
|
||||
"cmd.inspect_center_of_mass": "Центр мас",
|
||||
"cmd.inspect_compare": "Порівняти тіла",
|
||||
@@ -416,7 +353,6 @@
|
||||
"cmd.inspect_minimum_radius": "Аналіз мінімального радіуса",
|
||||
"cmd.inspect_zebra": "Зебра-аналіз",
|
||||
"cmd.joint_as_built": "З'єднання за поточним положенням",
|
||||
"cmd.joint_cam": "Кулачок",
|
||||
"cmd.joint_create": "З'єднання",
|
||||
"cmd.joint_delete": "Видалити з'єднання",
|
||||
"cmd.joint_drive": "Керувати з'єднаннями",
|
||||
@@ -447,11 +383,8 @@
|
||||
"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_keep": "Зберегти траєкторію руху",
|
||||
@@ -484,15 +417,6 @@
|
||||
"cmd.plastic_rules": "Список правил пластику",
|
||||
"cmd.plastic_snap_fit": "Клацкове з'єднання",
|
||||
"cmd.render_backends": "Рендер-бекенди",
|
||||
"cmd.render_cancel": "Скасувати рендеринг",
|
||||
"cmd.render_export": "Експортувати зображення рендерингу",
|
||||
"cmd.render_preflight": "Перевірити запит на рендеринг",
|
||||
"cmd.render_scene": "Переглянути сцену рендерингу",
|
||||
"cmd.render_settings_apply": "Застосувати камеру рендерингу",
|
||||
"cmd.render_settings_get": "Налаштування рендерингу",
|
||||
"cmd.render_settings_set": "Зберегти налаштування рендерингу",
|
||||
"cmd.render_start": "Рендеринг зображення",
|
||||
"cmd.render_status": "Перебіг рендерингу",
|
||||
"cmd.select_clear": "Зняти виділення",
|
||||
"cmd.sheet_convert": "Перетворити на листовий метал",
|
||||
"cmd.sheet_export_bend_table": "Експортувати таблицю згинів",
|
||||
@@ -640,7 +564,6 @@
|
||||
"coupling.rack": "Рейка",
|
||||
"coupling.radius_1": "Радіус 1",
|
||||
"coupling.radius_2": "Радіус 2",
|
||||
"dialog.computing": "Обчислення… {seconds} с",
|
||||
"dialog.custom_axis": "↖ Власна вісь",
|
||||
"dialog.edit_title": "РЕДАГУВАННЯ {title}",
|
||||
"dialog.select": "↖ Вибрати",
|
||||
@@ -650,25 +573,10 @@
|
||||
"dialog.step": "Крок",
|
||||
"document.save_changes": "Зберегти зміни в {name}?",
|
||||
"document.unsaved_changes": "У {name} є незбережені зміни. Якщо не зберегти, вони будуть втрачені.",
|
||||
"drive.stopped_by_contact": "Зупинка на {value}: {a} пройшло б крізь {b}",
|
||||
"drive.stopped_by_loop": "Зупинка на {value}: контур через {joint} далі не замикається",
|
||||
"drive.unconnected": "Нічого не рухається: {part} не з'єднано ні з чим закріпленим",
|
||||
"expression, e.g. 25 mm": "вираз, напр. 25 mm",
|
||||
"fits the face, e.g. M8": "відповідає грані, напр. M8",
|
||||
"from the rule": "з правила",
|
||||
"home.documentation": "Документація",
|
||||
"home.in_this_browser": "у цьому браузері",
|
||||
"home.missing": "відсутній",
|
||||
"home.open": "Відкрити…",
|
||||
"home.opened_days_ago": "Відкрито {count} дн. тому",
|
||||
"home.opened_hours_ago": "Відкрито {count} год тому",
|
||||
"home.opened_just_now": "Щойно відкрито",
|
||||
"home.opened_minutes_ago": "Відкрито {count} хв тому",
|
||||
"home.opening": "відкриття…",
|
||||
"home.recent": "Недавні",
|
||||
"home.report_issue": "Повідомити про проблему",
|
||||
"home.samples": "Зразки",
|
||||
"home.whats_new": "Що нового",
|
||||
"install.button_tip": "Встановити SolidCraft як застосунок: він відкривається в окремому вікні й працює без мережі",
|
||||
"install.dock_1": "Виберіть «Файл» › «Додати в Dock».",
|
||||
"install.dock_2": "Натисніть «Додати».",
|
||||
@@ -684,16 +592,6 @@
|
||||
"joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці.",
|
||||
"joint.one_body": "Обидва вибори на {body}. Виберіть другий на іншій деталі.",
|
||||
"joint.one_component": "Ці деталі - тіла одного компонента: {bodies}. З'єднання рухає один компонент відносно іншого, тому кожній деталі потрібен власний компонент.",
|
||||
"motion.checked_to": "Перевірено лише до кроку {step}: перевірка вичерпала свій бюджет роботи",
|
||||
"motion.collision": "{a} · {b}: кроки {steps}",
|
||||
"motion.duration_hint": "секунди (порожньо: на крок)",
|
||||
"motion.no_collisions": "За все дослідження зіткнень немає",
|
||||
"nav.touchpad.help": "Утримуйте Shift і рухайте вказівник, щоб панорамувати; утримуйте Alt/Option і рухайте, щоб обертати. Кнопка миші не потрібна. Вертикальна прокрутка масштабує.",
|
||||
"nav.touchpad.label": "Трекпад",
|
||||
"nav.touchpad.orbit": "Обертання (утримуйте Alt/Option і рухайте; без кнопки миші)",
|
||||
"nav.touchpad.pan": "Панорамування (утримуйте Shift і рухайте; без кнопки миші)",
|
||||
"nav.touchpad.scroll": "Трекпад використовує вертикальну прокрутку для масштабування. Ваше налаштування панорамування двома пальцями зберігається для інших наборів.",
|
||||
"nav.touchpad.zoom": "Масштаб (вертикальна прокрутка або стискання)",
|
||||
"needs two joints": "потрібні два з'єднання",
|
||||
"new configuration": "нова конфігурація",
|
||||
"new name": "нова назва",
|
||||
@@ -708,60 +606,6 @@
|
||||
"pattern.flip_direction": "Змінити напрямок",
|
||||
"pick a hole to seat it, or OK places it at the origin": "виберіть отвір для посадки, або OK розмістить його в початку координат",
|
||||
"pick one or two vertices, edges or faces": "виберіть одну-дві вершини, ребра або грані",
|
||||
"render.background": "Фон сцени",
|
||||
"render.fit": "Вписати виріб",
|
||||
"render.image_cancel": "Скасувати рендеринг",
|
||||
"render.image_cancelled": "Рендеринг скасовано",
|
||||
"render.image_cancelling": "Скасування",
|
||||
"render.image_check": "Перевірити запит на рендеринг",
|
||||
"render.image_completed": "Зображення готове до експорту",
|
||||
"render.image_encoding": "Кодування PNG",
|
||||
"render.image_export": "Експортувати PNG",
|
||||
"render.image_failed": "Рендеринг не вдався",
|
||||
"render.image_height": "Висота",
|
||||
"render.image_help": "Попереднє зображення на CPU · PNG · наближена прозорість",
|
||||
"render.image_overwrite": "Замінити наявний файл",
|
||||
"render.image_preparing": "Підготовка зображення",
|
||||
"render.image_queued": "Очікує рендерингу",
|
||||
"render.image_reduce": "Спробуйте менше зображення або простішу сцену.",
|
||||
"render.image_running": "Рендеринг зображення",
|
||||
"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.navigation_help": "Камера рухається так само, як у режимі проєктування (Налаштування › Навігація). «Зберегти налаштування» фіксує поточну камеру.",
|
||||
"render.opaque_image_summary": "Попередній PNG · непрозорий PBR · змішана прозорість",
|
||||
"render.opaque_preview_help": "Непрозорий PBR і прості кольори; змішана прозорість. Заломлення, HDRI та фінальний рендеринг поки недоступні.",
|
||||
"render.perspective": "Перспективна камера",
|
||||
"render.preview": "Вбудований попередній перегляд",
|
||||
"render.preview_help": "Растрове затінення та змішана прозорість. Заломлення, HDRI та фінальний рендеринг поки недоступні.",
|
||||
"render.reload_settings": "Перезавантажити збережені налаштування",
|
||||
"render.restore_camera": "Відновити збережену камеру",
|
||||
"render.return_design": "Повернутися до проєктування",
|
||||
"render.save_setup": "Зберегти налаштування",
|
||||
"render.setup_name": "Назва налаштування",
|
||||
"render.unavailable_preview": "Це налаштування вимагає недоступного профілю попереднього перегляду.",
|
||||
"render.unsaved": "Незбережені зміни попереднього перегляду",
|
||||
"render.use_preview": "Використати вбудований попередній перегляд",
|
||||
"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": "Вентиляційна пластина",
|
||||
"settings.display_quality_note": "Дрібніші рівні малюють криві грані й ребра плавнішими, але тріангуляція триває довше. Змінюється лише вікно перегляду, ніколи не проєкт чи експорт.",
|
||||
"settings.frame_rate_note": "Показує кадри за секунду в правому нижньому куті виду. Поки це ввімкнено, вид перемальовується безперервно.",
|
||||
"settings.measure_axis_distances": "Відстані X/Y/Z",
|
||||
"settings.measure_axis_distances_help": "Показувати розміри вздовж світових осей разом із загальною відстанню, поки відкрите вікно вимірювання.",
|
||||
"settings.msaa_applies_on_restart": "Згладжування застосується під час наступного запуску SolidCraft",
|
||||
@@ -769,7 +613,6 @@
|
||||
"settings.msaa_unsupported": "Не підтримується цим графічним пристроєм",
|
||||
"settings.reset_intro": "Ці налаштування не працюють на цьому комп'ютері й не давали б SolidCraft запуститися, тому їх змінено:",
|
||||
"settings.reset_title": "Налаштування було змінено",
|
||||
"settings.supersampling_note": "Малює вид у вищій роздільності й потім зменшує його: плавніші ребра, лінії та сітка на екранах до 4K. Це коштує часу GPU: приблизно 2,25× пікселів за 1,5× і 4× за 2×.",
|
||||
"sketch.degrees_of_freedom": "{count} ступенів вільності",
|
||||
"sketch.draw_curves": "Малювати як {linetype}",
|
||||
"sketch.make_selection": "Перетворити виділене на {linetype}",
|
||||
@@ -793,9 +636,6 @@
|
||||
"timeline.reorder_many": "Перевпорядкувати операції",
|
||||
"timeline.ungroup": "Прибрати теки операцій",
|
||||
"to the next face": "до наступної грані",
|
||||
"toolbar.image": "ЗОБРАЖЕННЯ",
|
||||
"toolbar.render": "РЕНДЕР",
|
||||
"toolbar.render_scene": "СЦЕНА",
|
||||
"trace.points": "{count} точок на траєкторії",
|
||||
"trace.stopped_by_contact": "Закінчується на відліку {sample}: {a} пройшов би крізь {b}",
|
||||
"trace.stopped_by_loop": "Закінчується на відліку {sample}: контур через {joint} далі не замикається",
|
||||
@@ -806,162 +646,8 @@
|
||||
"ui.about": "Про програму",
|
||||
"ui.activate": "Активувати",
|
||||
"ui.active_component": "Активний компонент",
|
||||
"ui.agent_chat": "Чат з агентом",
|
||||
"ui.agent_chat_allow": "Дозволити",
|
||||
"ui.agent_chat_allowed": "Дозволено",
|
||||
"ui.agent_chat_answered": "Відповідь: {option}",
|
||||
"ui.agent_chat_approval": "Дозволити агенту це зробити?",
|
||||
"ui.agent_chat_attach_view": "Прикріпити вид",
|
||||
"ui.agent_chat_attach_view_tip": "Надіслати знімок поточного виду разом із повідомленням",
|
||||
"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_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_hint": "Будь-яка програма, що підтримує Agent Client Protocol через stdin і stdout. Оболонка її не запускає.",
|
||||
"ui.agent_chat_denied": "Відхилено",
|
||||
"ui.agent_chat_deny": "Відхилити",
|
||||
"ui.agent_chat_desktop_only": "Чат з агентом потребує настільної програми.",
|
||||
"ui.agent_chat_detecting": "Пошук агентів…",
|
||||
"ui.agent_chat_dock_left": "Закріпити ліворуч",
|
||||
"ui.agent_chat_dock_right": "Закріпити праворуч",
|
||||
"ui.agent_chat_edit": "Редагувати",
|
||||
"ui.agent_chat_exited": "Агент зупинився.",
|
||||
"ui.agent_chat_failed_start": "Не вдалося запустити агента: {error}",
|
||||
"ui.agent_chat_intro": "Спілкуйтеся з агентом для програмування, яким уже користуєтеся, або з обраною вами модельною кінцевою точкою. Він працює з відкритим проєктом через інструменти SolidCraft: його зміни з'являються в міру виконання й скасовуються одним кроком на повідомлення. Що він може робити без запиту, задано в Налаштування > ШІ.",
|
||||
"ui.agent_chat_key_in_env": "ключ задано",
|
||||
"ui.agent_chat_left": "Ліворуч",
|
||||
"ui.agent_chat_limit": "Агент досяг межі {limit} змін на одне повідомлення. Надішліть інше повідомлення, щоб дозволити йому продовжити.",
|
||||
"ui.agent_chat_minimize": "Згорнути до смужки",
|
||||
"ui.agent_chat_model_tip": "Модель, яку використовує агент. Ваш вибір запам'ятовується для цього агента.",
|
||||
"ui.agent_chat_new": "Новий чат",
|
||||
"ui.agent_chat_new_confirm": "Почати новий чат? Поточний буде очищено.",
|
||||
"ui.agent_chat_new_yes": "Новий чат",
|
||||
"ui.agent_chat_no_cli": "solidcraft-cli не знайдено поруч із програмою, тож агент не може дістатися до проєкту.",
|
||||
"ui.agent_chat_no_control": "Кінцева точка чату з агентом не запустилася, тож агент не може дістатися до проєкту.",
|
||||
"ui.agent_chat_no_images": "Цей агент не приймає зображень",
|
||||
"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_permission": "Агент просить виконати: {title}",
|
||||
"ui.agent_chat_pick": "Агент",
|
||||
"ui.agent_chat_placeholder": "Попросіть агента змінити проєкт…",
|
||||
"ui.agent_chat_placeholder_busy": "Поставте повідомлення в чергу, доки агент завершить (Ctrl+Enter: надіслати зараз)",
|
||||
"ui.agent_chat_privacy": "Нічого нікуди не надсилається, крім агента, який ви запускаєте, під вашим власним обліковим записом.",
|
||||
"ui.agent_chat_privacy_note": "SolidCraft нічого нікуди не надсилає: агент, який ви запускаєте, спілкується з власним сервісом під вашим обліковим записом. SolidCraft ніколи не бачить і не зберігає ключ чи пароль.",
|
||||
"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_remove": "Прибрати з черги",
|
||||
"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_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_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_undo_changes": "Скасувати ці зміни",
|
||||
"ui.agent_chat_undo_label": "Чат з агентом: {message}",
|
||||
"ui.agent_chat_undone": "(скасовано)",
|
||||
"ui.agent_chat_view_attached": "Вид прикріплено",
|
||||
"ui.agent_cursor": "Курсор агента",
|
||||
"ui.agent_cursor_speed": "Швидкість курсора агента",
|
||||
"ui.ai_add": "Додати",
|
||||
"ui.ai_add_agent": "Додати агента…",
|
||||
"ui.ai_add_agent_title": "Додати агента",
|
||||
"ui.ai_add_api": "API, сумісний з OpenAI",
|
||||
"ui.ai_add_custom": "Власна команда",
|
||||
"ui.ai_add_installed": "Встановлений агент",
|
||||
"ui.ai_add_installed_note": "Ваш власний запис для встановленого агента, наприклад з іншими аргументами. Встановлені агенти перелічуються окремо.",
|
||||
"ui.ai_added": "додано",
|
||||
"ui.ai_agent_mode_tip": "Власний режим агента: його власні інструменти (оболонка, редагування файлів) підкоряються йому. Інструменти SolidCraft підкоряються дозволам у Налаштування > ШІ.",
|
||||
"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": "ШІ",
|
||||
"ui.ai_copy_suffix": "копія",
|
||||
"ui.ai_custom_url": "Власна URL-адреса",
|
||||
"ui.ai_default": "Типовий",
|
||||
"ui.ai_http_busy": "кінцева точка зайнята або перевищила ліміт; спробуйте пізніше",
|
||||
"ui.ai_http_key": "кінцева точка відхилила ключ: перевірте його в Налаштування > ШІ",
|
||||
"ui.ai_http_not_found": "немає такої кінцевої точки чи моделі: перевірте базову URL-адресу й назву моделі",
|
||||
"ui.ai_key": "Ключ API",
|
||||
"ui.ai_key_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_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_modes_scope": "Ці налаштування стосуються інструментів SolidCraft. Власні інструменти агента (його оболонка, його редагування файлів) підкоряються власному режиму агента, який ви вибираєте в заголовку панелі чату, коли агент має режими.",
|
||||
"ui.ai_name": "Назва",
|
||||
"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_remove": "Видалити",
|
||||
"ui.ai_request_limit": "зупинено після 24 запитів на одне повідомлення; надішліть інше повідомлення, щоб продовжити",
|
||||
"ui.ai_reset": "Скинути",
|
||||
"ui.ai_settings": "Налаштування ШІ…",
|
||||
"ui.ai_show_features": "Показувати функції ШІ",
|
||||
"ui.ai_show_features_note": "Чат з агентом: панель, де агент для програмування, яким ви вже користуєтеся, або обрана вами модельна кінцева точка працює з відкритим проєктом. Вимкнено: немає кнопки ШІ, комбінації клавіш, пункту меню чи панелі, і нічого не шукається та не запускається.",
|
||||
"ui.ai_switch_tip": "Змінити агента для цієї розмови",
|
||||
"ui.ai_test": "Перевірити",
|
||||
"ui.ai_test_acp_ok": "Відповідає: {agent}",
|
||||
"ui.ai_test_acp_tip": "Ненадовго запускає агента й запитує сесію; потім завершує його",
|
||||
"ui.ai_test_api_tip": "Запитує в кінцевої точки її моделі",
|
||||
"ui.ai_test_no_model": "Досягнуто: {count} моделей, але не {model}",
|
||||
"ui.ai_test_ok": "Досягнуто: {count} моделей",
|
||||
"ui.ai_testing": "Перевірка…",
|
||||
"ui.ai_tool_done": "готово",
|
||||
"ui.ai_tool_failed": "не вдалося",
|
||||
"ui.ai_tool_running": "виконується",
|
||||
"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.all": "Усі",
|
||||
"ui.analysis": "Аналіз",
|
||||
"ui.angle": "Кут",
|
||||
@@ -978,7 +664,6 @@
|
||||
"ui.axes": "Осі",
|
||||
"ui.axis": "Вісь",
|
||||
"ui.base_point": "Базова точка",
|
||||
"ui.blocked": "Заблоковані",
|
||||
"ui.bodies": "Тіла",
|
||||
"ui.box": "Куб",
|
||||
"ui.break": "Розірвати",
|
||||
@@ -1004,21 +689,6 @@
|
||||
"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.combine": "Об'єднати",
|
||||
"ui.coming_later": "з'явиться пізніше",
|
||||
"ui.command_done": "{command} виконано",
|
||||
@@ -1043,8 +713,6 @@
|
||||
"ui.curvature": "Кривизна",
|
||||
"ui.curvature_g2": "Кривизна (G2)",
|
||||
"ui.curves": "Криві",
|
||||
"ui.custom_program": "Власна…",
|
||||
"ui.custom_program_tip": "Виберіть програму-слайсер, щоб додати її до списку",
|
||||
"ui.customizeToolbar": "Налаштувати панель інструментів…",
|
||||
"ui.cut": "Вирізати",
|
||||
"ui.cylinder": "Циліндр",
|
||||
@@ -1054,25 +722,9 @@
|
||||
"ui.delete": "Видалити",
|
||||
"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.diameter": "Діаметр",
|
||||
"ui.dimension": "Розмір",
|
||||
"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",
|
||||
@@ -1112,8 +764,6 @@
|
||||
"ui.fix_unfix": "Закріпити/розкріпити",
|
||||
"ui.flat": "Плоска",
|
||||
"ui.flip": "Перевернути",
|
||||
"ui.format": "Формат",
|
||||
"ui.frame_rate": "Частота кадрів",
|
||||
"ui.front": "Спереду",
|
||||
"ui.fully_constrained": "Повністю визначений",
|
||||
"ui.general": "Загальні",
|
||||
@@ -1166,7 +816,6 @@
|
||||
"ui.heading_rectangular_pattern": "ПРЯМОКУТНИЙ МАСИВ",
|
||||
"ui.heading_revolve": "ОБЕРТАННЯ",
|
||||
"ui.heading_right": "СПРАВА",
|
||||
"ui.heading_save_mesh": "ЗБЕРЕГТИ ЯК СІТКУ",
|
||||
"ui.heading_scale": "МАСШТАБ",
|
||||
"ui.heading_section_analysis": "АНАЛІЗ ПЕРЕРІЗУ",
|
||||
"ui.heading_select": "ВИБІР",
|
||||
@@ -1241,9 +890,6 @@
|
||||
"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.midpoint": "Середня точка",
|
||||
"ui.mirror": "Дзеркало",
|
||||
"ui.mirror_line": "Вісь дзеркала",
|
||||
@@ -1256,10 +902,8 @@
|
||||
"ui.newSketchGroup": "Нова група ескізів",
|
||||
"ui.new_body": "Нове тіло",
|
||||
"ui.new_design": "Новий проєкт",
|
||||
"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 вгору",
|
||||
@@ -1305,14 +949,12 @@
|
||||
"ui.project": "Проєктувати",
|
||||
"ui.project_face_edges_sketch": "Проєктувати ребра граней у нові ескізи",
|
||||
"ui.properties": "Властивості",
|
||||
"ui.pull_direction": "Напрямок витягування",
|
||||
"ui.quantity": "Кількість",
|
||||
"ui.quantity_2": "Кількість 2",
|
||||
"ui.quit": "Вихід",
|
||||
"ui.radial_context_menu": "Кругове контекстне меню",
|
||||
"ui.radius": "Радіус",
|
||||
"ui.radius_type": "Тип радіуса",
|
||||
"ui.reachable": "Досяжні",
|
||||
"ui.rectangle": "Прямокутник",
|
||||
"ui.rectangular_pattern": "Прямокутний масив",
|
||||
"ui.redo": "Повторити",
|
||||
@@ -1333,10 +975,6 @@
|
||||
"ui.save": "Зберегти",
|
||||
"ui.save_as": "Зберегти як",
|
||||
"ui.save_as_ellipsis": "Зберегти як...",
|
||||
"ui.save_mesh_no_slicer": "Слайсер не знайдено: виберіть «Власна…» і вкажіть свою програму-слайсер або вимкніть «Надіслати в слайсер»",
|
||||
"ui.save_mesh_pick_bodies": "Виберіть тіла для збереження",
|
||||
"ui.save_mesh_temp_failed": "Не вдалося створити {folder}: {error}",
|
||||
"ui.saved_to": "Збережено {path}",
|
||||
"ui.scale": "Масштаб",
|
||||
"ui.section_analysis": "Аналіз перерізу",
|
||||
"ui.select": "Вибрати",
|
||||
@@ -1344,9 +982,6 @@
|
||||
"ui.selectTangentChain": "Вибрати дотичний ланцюг",
|
||||
"ui.select_other_hint": "Вибір іншого: утримуйте ліву кнопку нерухомо на моделі (або клацніть правою › Вибрати інше…), щоб побачити список усього під курсором; клацніть ще раз у тому ж місці, щоб вибрати наступний об'єкт там.",
|
||||
"ui.selection": "Виділення",
|
||||
"ui.send": "Надіслати",
|
||||
"ui.send_to_slicer": "Надіслати в слайсер",
|
||||
"ui.sent_to_slicer": "Надіслано в {slicer}",
|
||||
"ui.shell": "Оболонка",
|
||||
"ui.show": "Показати",
|
||||
"ui.showAll": "Показати все",
|
||||
@@ -1371,8 +1006,6 @@
|
||||
"ui.sketch_status": "Стан ескізу",
|
||||
"ui.sketches": "Ескізи",
|
||||
"ui.slice": "Розріз",
|
||||
"ui.slicer": "Слайсер",
|
||||
"ui.slicer_delete_tip": "{program}\nНатисніть Delete, щоб прибрати його зі списку",
|
||||
"ui.slot": "Паз",
|
||||
"ui.smooth": "Плавний",
|
||||
"ui.smooth_wheel_zoom": "Плавне масштабування колесом",
|
||||
@@ -1388,9 +1021,6 @@
|
||||
"ui.stand_up_tip": "Після відкриття файлу STEP або IGES з напрямком Z вгору пропонувати поворот на чверть оберту навколо X",
|
||||
"ui.start": "Початок",
|
||||
"ui.start_radius": "Початковий радіус",
|
||||
"ui.supersampling": "Наддискретизація (SSAA)",
|
||||
"ui.supersampling_adaptive": "Лише коли вид нерухомий",
|
||||
"ui.supersampling_off": "Вимкнено (1×)",
|
||||
"ui.suppress": "Придушити",
|
||||
"ui.sweep": "Протягування",
|
||||
"ui.sweep_follow_direction": "Слідувати напрямку",
|
||||
@@ -1411,7 +1041,6 @@
|
||||
"ui.timeline_left_sidebar": "Ліва бічна панель",
|
||||
"ui.tip_angle": "Кут вістря",
|
||||
"ui.to_object": "До об'єкта",
|
||||
"ui.tool_direction": "Напрямок інструмента",
|
||||
"ui.top": "Зверху",
|
||||
"ui.torus": "Тор",
|
||||
"ui.total_angle": "Загальний кут",
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
"A new configuration, a copy of the active one": "新建配置,为当前配置的副本",
|
||||
"AI": "AI",
|
||||
"About SolidCraft": "关于 SolidCraft",
|
||||
"Acceleration": "加速度",
|
||||
"Active": "活动",
|
||||
"Active rule": "活动规则",
|
||||
"Add": "添加",
|
||||
@@ -15,10 +14,8 @@
|
||||
"Add Mid Radius": "添加中间半径",
|
||||
"Add Row": "添加行",
|
||||
"Add condition": "添加条件",
|
||||
"Against": "对照",
|
||||
"Alignment": "对齐",
|
||||
"All Sketch Points": "所有草图点",
|
||||
"All components": "所有零部件",
|
||||
"All open designs": "所有打开的设计",
|
||||
"Allowed expressions, separated by semicolons": "允许的表达式,以分号分隔",
|
||||
"Also deletes": "同时删除",
|
||||
@@ -60,7 +57,6 @@
|
||||
"Configuration rules": "配置规则",
|
||||
"Construction": "构造",
|
||||
"Contact": "接触",
|
||||
"Contact sets": "接触集",
|
||||
"Continuity": "连续性",
|
||||
"Copy Error Message": "复制错误消息",
|
||||
"Copy Warning Message": "复制警告消息",
|
||||
@@ -91,13 +87,11 @@
|
||||
"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": "在视图中双击中键:主视图(主视图,框住所显示的内容)、适合窗口(框住所显示的内容,保持方向)或无动作",
|
||||
"Drive Joint": "驱动接头",
|
||||
"Duration": "时长",
|
||||
"Edges": "边",
|
||||
"Edit Profile Sketch": "编辑轮廓草图",
|
||||
"Enable rule": "启用规则",
|
||||
"Enabled": "已启用",
|
||||
"Explode": "爆炸",
|
||||
"Export Animation…": "导出动画…",
|
||||
"Export Current View as DXF": "将当前视图导出为DXF",
|
||||
"Export Current View as DXF…": "将当前视图导出为DXF…",
|
||||
"Export DXF…": "导出DXF…",
|
||||
@@ -155,7 +149,6 @@
|
||||
"Move earlier": "向前移动",
|
||||
"Move later": "向后移动",
|
||||
"Name": "名称",
|
||||
"New study": "新建研究",
|
||||
"No crash reports.": "没有崩溃报告。",
|
||||
"No matching appearances": "没有匹配的外观",
|
||||
"No visible bodies to export.": "没有可导出的可见实体。",
|
||||
@@ -174,10 +167,8 @@
|
||||
"Per Edge": "每条边",
|
||||
"Pick the tool bodies": "选择工具实体",
|
||||
"Picked": "所选",
|
||||
"Picked point": "选取的点",
|
||||
"Place at the origin instead": "改为放置在原点",
|
||||
"Playback": "播放",
|
||||
"Plot": "图表",
|
||||
"Position": "位置",
|
||||
"Position (0 to 1)": "位置(0 到 1)",
|
||||
"Position (G0)": "位置 (G0)",
|
||||
@@ -186,7 +177,6 @@
|
||||
"Preview leaves the current design unchanged.": "预览不会更改当前设计。",
|
||||
"Profiles/Curves": "轮廓/曲线",
|
||||
"Projection": "投影",
|
||||
"Quantity": "物理量",
|
||||
"RECENT": "最近使用",
|
||||
"RULED SURFACE": "直纹曲面",
|
||||
"Radius Fit": "半径拟合",
|
||||
@@ -221,7 +211,6 @@
|
||||
"Round": "圆角",
|
||||
"Rule": "规则",
|
||||
"Save Rule": "保存规则",
|
||||
"Save the study as an animated GIF, seen as the viewport shows it": "按视口中的显示将研究保存为动画 GIF",
|
||||
"Saved preview. Geometry is being checked before editing.": "已保存预览。编辑前正在检查几何。",
|
||||
"Scale factor": "比例因子",
|
||||
"Search": "搜索",
|
||||
@@ -252,7 +241,6 @@
|
||||
"Stand this part up?": "立起此零件?",
|
||||
"Step": "步骤",
|
||||
"Steps": "步数",
|
||||
"Study": "研究",
|
||||
"Style": "样式",
|
||||
"Suppressed": "已抑制",
|
||||
"Swap Ends": "交换端点",
|
||||
@@ -282,7 +270,6 @@
|
||||
"Use selected face as fixed plane": "使用所选面作为固定平面",
|
||||
"VIEW": "视图",
|
||||
"Value": "值",
|
||||
"Velocity": "速度",
|
||||
"Vertices": "顶点",
|
||||
"View navigator": "视图导航器",
|
||||
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "仅导出可见实体。曲线以线段近似(公差0.01毫米)。",
|
||||
@@ -306,13 +293,6 @@
|
||||
"browser.precision": "精度: {precision}",
|
||||
"browser.sketch_name": "草图{number}",
|
||||
"browser.units": "单位: {units}",
|
||||
"cam.flat": "平底",
|
||||
"cam.follower": "从动件",
|
||||
"cam.knife": "尖顶",
|
||||
"cam.needs_joints": "需要一个旋转接头和一个滑动或摆动接头",
|
||||
"cam.roller": "滚子",
|
||||
"cam.roller_pick": "滚子(可选)",
|
||||
"cam.tip_pick": "尖端(可选)",
|
||||
"cmd.appearance_assign": "外观",
|
||||
"cmd.appearance_library": "外观库",
|
||||
"cmd.appearance_list": "列出外观",
|
||||
@@ -416,7 +396,6 @@
|
||||
"cmd.inspect_minimum_radius": "最小半径分析",
|
||||
"cmd.inspect_zebra": "斑马纹分析",
|
||||
"cmd.joint_as_built": "现状接头",
|
||||
"cmd.joint_cam": "凸轮",
|
||||
"cmd.joint_create": "接头",
|
||||
"cmd.joint_delete": "删除接头",
|
||||
"cmd.joint_drive": "驱动接头",
|
||||
@@ -447,11 +426,8 @@
|
||||
"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_keep": "保留运动轨迹",
|
||||
@@ -655,18 +631,6 @@
|
||||
"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": "仅导出可见实体。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。",
|
||||
"expression, e.g. 25 mm": "表达式,例如 25 mm",
|
||||
"fits the face, e.g. M8": "适配该面,例如 M8",
|
||||
"from the rule": "来自规则",
|
||||
@@ -698,10 +662,6 @@
|
||||
"joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。",
|
||||
"joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。",
|
||||
"joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。",
|
||||
"motion.checked_to": "仅检查到第 {step} 步:检查已用完其工作量上限",
|
||||
"motion.collision": "{a} · {b}:第 {steps} 步",
|
||||
"motion.duration_hint": "秒(留空:按步)",
|
||||
"motion.no_collisions": "整个研究中没有碰撞",
|
||||
"nav.touchpad.help": "按住 Shift 并移动指针可平移;按住 Alt/Option 并移动可旋转。无需按鼠标按钮。垂直滚动可缩放。",
|
||||
"nav.touchpad.label": "触控板",
|
||||
"nav.touchpad.orbit": "旋转(按住 Alt/Option 并移动,无需鼠标按钮)",
|
||||
@@ -800,10 +760,6 @@
|
||||
"sketch_text.path_hint": "文字所跟随的草图曲线:先单击此处,再选择曲线",
|
||||
"sketch_text.use_font_file": "使用字体文件 {path}",
|
||||
"the parts library is not available": "零件库不可用",
|
||||
"thread.automatic_size": "自动尺寸",
|
||||
"thread.designation": "螺纹标记",
|
||||
"thread.iso_metric": "ISO 公制",
|
||||
"thread.select_size": "选择尺寸",
|
||||
"timeline.group": "新建特征文件夹",
|
||||
"timeline.move_many": "移动时间线项目",
|
||||
"timeline.move_to_group": "将特征移至文件夹",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
struct U {
|
||||
vp: mat4x4<f32>,
|
||||
back: vec4<f32>, // xyz = toward the eye, w = 1 for linear output
|
||||
screen: vec4<f32>, // viewport width, height (px), unused, silhouettes on (1)
|
||||
screen: vec4<f32>, // viewport width, height (px), depth bias (see `biased_z`), silhouettes on (1)
|
||||
clip: vec4<f32>, // section plane: normal, d (zero normal: no section)
|
||||
cap: vec4<f32>, // colour of the inside of cut bodies
|
||||
ana: vec4<f32>, // surface analysis: mode (1 zebra, 2 draft, 3 curvature), parameter
|
||||
@@ -14,19 +14,8 @@ struct U {
|
||||
// blocked; curvature flat, middle, tight
|
||||
ana_c: array<vec4<f32>, 8>,
|
||||
ana_f: vec4<f32>, // x = 1: stripe the negative draft and blocked faces
|
||||
depth: vec4<f32>, // x = 1: reversed depth (1 near, 0 far); y, z: the faces' push (`FACE_BIAS`)
|
||||
};
|
||||
|
||||
fn reversed() -> bool {
|
||||
return u.depth.x > 0.5;
|
||||
}
|
||||
|
||||
/// Clip-space depth measured the usual way (0 at the near plane, w at the far one), whichever
|
||||
/// way the depth buffer runs.
|
||||
fn near_z(c: vec4<f32>) -> f32 {
|
||||
return select(c.z, c.w - c.z, reversed());
|
||||
}
|
||||
|
||||
@group(1) @binding(2) var acc_t: texture_2d<f32>;
|
||||
|
||||
fn clipped(p: vec3<f32>) -> bool {
|
||||
@@ -81,22 +70,11 @@ struct CutOut {
|
||||
@fragment
|
||||
fn fs_solid_cut(i: TOut, @builtin(front_facing) front: bool) -> CutOut {
|
||||
var o: CutOut;
|
||||
// Derivatives (in `pushed`) first, before `solid` may discard.
|
||||
o.depth = pushed(cap_depth(i.wp, i.pos.z));
|
||||
o.c = solid(i, front);
|
||||
o.depth = cap_depth(i.wp, i.pos.z);
|
||||
return o;
|
||||
}
|
||||
|
||||
/// A depth the shader writes itself, pushed back like the faces the GPU pushes (`FACE_BIAS`,
|
||||
/// which does not apply then): its own slope over `depth.z` pixels and `depth.y` depth steps.
|
||||
fn pushed(z: f32) -> f32 {
|
||||
let slope = max(abs(dpdx(z)), abs(dpdy(z)));
|
||||
// One step: 2⁻²⁴ in a 24-bit buffer; a float buffer's steps follow the value (2⁻²³ of it).
|
||||
let step = select(1.0 / 16777216.0, abs(z) * 1.1920929e-7, reversed());
|
||||
let push = slope * u.depth.z + step * u.depth.y;
|
||||
return clamp(z - select(-push, push, reversed()), 0.0, 1.0);
|
||||
}
|
||||
|
||||
/// Depth of the section plane on the view ray through `wp` (a far wall seen through the cut),
|
||||
/// never behind the wall itself (`z`).
|
||||
fn cap_depth(wp: vec3<f32>, z: f32) -> f32 {
|
||||
@@ -107,7 +85,6 @@ fn cap_depth(wp: vec3<f32>, z: f32) -> f32 {
|
||||
let p = wp + dir * ((u.clip.w - dot(u.clip.xyz, wp)) / dn);
|
||||
let c = u.vp * vec4<f32>(p, 1.0);
|
||||
if (c.w <= 0.0) { return z; }
|
||||
if (reversed()) { return clamp(c.z / c.w, z, 1.0); }
|
||||
return clamp(c.z / c.w, 0.0, z);
|
||||
}
|
||||
|
||||
@@ -246,8 +223,28 @@ fn shade(i: TOut) -> vec4<f32> {
|
||||
return out_color(vec4<f32>(min(i.c.rgb * k + vec3<f32>(spec), vec3<f32>(1.0)), i.c.a));
|
||||
}
|
||||
|
||||
// Lines, decals and ghosts are drawn at their own depth: opaque faces are pushed back by their
|
||||
// slope instead (`FACE_BIAS`, #1434), so what lies on a face draws over it at any angle.
|
||||
/// Clip-space z of `p` (clipped to `c`) pulled `s` depth biases toward the eye (pushed away
|
||||
/// when negative). Orthographic depth is linear in distance, so the bias is a fixed step of it.
|
||||
/// Perspective depth is not: near the far plane a fixed step spans tens of millimetres (edges
|
||||
/// showed through walls), so the point moves toward the eye by a fraction of its distance.
|
||||
fn biased_z(p: vec3<f32>, c: vec4<f32>, s: f32) -> f32 {
|
||||
if (u.eye.w > 0.5) {
|
||||
let q = u.vp * vec4<f32>(mix(p, u.eye.xyz, u.screen.z * 8.0 * s), 1.0);
|
||||
return q.z / max(q.w, 1e-6) * c.w;
|
||||
}
|
||||
return c.z - u.screen.z * s * c.w;
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_ghost(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: vec4<f32>) -> TOut {
|
||||
var o: TOut;
|
||||
o.pos = u.vp * vec4<f32>(p, 1.0);
|
||||
o.pos.z = biased_z(p, o.pos, -4.0);
|
||||
o.n = n;
|
||||
o.c = c;
|
||||
o.wp = p;
|
||||
return o;
|
||||
}
|
||||
|
||||
struct LOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@@ -264,14 +261,12 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(
|
||||
// An end behind the near plane (clip z < 0) has no screen point: its divide flips the
|
||||
// line or drops it whole (ground grid lines running past the eye at a low angle). Cut
|
||||
// the segment at the plane instead; clip space is linear in the world point.
|
||||
let za = near_z(ca);
|
||||
let zb = near_z(cb);
|
||||
if (za < 0.0 && zb > 0.0) {
|
||||
let k = za / (za - zb);
|
||||
if (ca.z < 0.0 && cb.z > 0.0) {
|
||||
let k = ca.z / (ca.z - cb.z);
|
||||
ca = mix(ca, cb, k);
|
||||
pa = mix(a, b, k);
|
||||
} else if (zb < 0.0 && za > 0.0) {
|
||||
let k = zb / (zb - za);
|
||||
} else if (cb.z < 0.0 && ca.z > 0.0) {
|
||||
let k = cb.z / (cb.z - ca.z);
|
||||
cb = mix(cb, ca, k);
|
||||
pb = mix(b, a, k);
|
||||
}
|
||||
@@ -290,7 +285,7 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(
|
||||
let base = select(ca, cb, t > 0.5);
|
||||
let off = nrm * s * w * 0.5 + dir * (t * 2.0 - 1.0) * w * 0.5;
|
||||
var o: LOut;
|
||||
o.pos = vec4<f32>(base.xy + off / half * base.w, base.z, base.w);
|
||||
o.pos = vec4<f32>(base.xy + off / half * base.w, biased_z(select(pa, pb, t > 0.5), base, 1.0), base.w);
|
||||
o.c = c;
|
||||
o.wp = select(pa, pb, t > 0.5);
|
||||
return o;
|
||||
@@ -315,8 +310,9 @@ struct IOut {
|
||||
@vertex
|
||||
fn vs_img(@location(0) p: vec3<f32>, @location(1) uv: vec2<f32>, @location(2) a: f32) -> IOut {
|
||||
var o: IOut;
|
||||
// On a face it shows over it: the face is pushed back (`FACE_BIAS`).
|
||||
o.pos = u.vp * vec4<f32>(p, 1.0);
|
||||
// Pulled toward the eye like lines, so a decal on a face is not lost in it.
|
||||
o.pos.z = biased_z(p, o.pos, 1.0);
|
||||
o.uv = uv;
|
||||
o.a = a;
|
||||
o.wp = p;
|
||||
|
||||
@@ -21,8 +21,7 @@
|
||||
//! `|i: usize, n: usize| -> &'static str`; it may read the other fields;
|
||||
//! - `pinned`: a face pick that stays where it is when the feature moves;
|
||||
//! `pick_if = cond`: a face pick when `cond` holds, else a position;
|
||||
//! - `placement`: a primitive's placement point, or an optional one (its X, Y and Z expressions
|
||||
//! are not inputs);
|
||||
//! - `placement`: a primitive's placement point (its X, Y and Z expressions are not inputs);
|
||||
//! - `profiles_of = sketch_field`, optionally with `when = cond`: a profile selection;
|
||||
//! - `after = field`: visit this field right after `field` instead of in declaration order (where
|
||||
//! the parameter names already given need it);
|
||||
@@ -163,8 +162,7 @@ fn walk_field(b: &Ident, r: &Roles, which: Which, mutable: bool) -> Tokens {
|
||||
#w::Each::<#w::Vec3>::#each(#b, &mut |p| f(if #pick { #w::Geo::Pick(p) } else { #w::Geo::Pos(p) }));
|
||||
}
|
||||
}
|
||||
// A point or an optional one (a hole's `at`, #1678).
|
||||
Some(Geo::Placement) => quote! { #w::Each::<crate::PointExpr>::#each(#b, &mut |p| f(#w::Geo::Placement(p))); },
|
||||
Some(Geo::Placement) => quote! { f(#w::Geo::Placement(#b)); },
|
||||
Some(Geo::Profiles { .. }) => {
|
||||
let (id, when) = (pre(b, "sketch"), pre(b, "when"));
|
||||
quote! {
|
||||
|
||||
@@ -563,10 +563,6 @@ pub enum FeatureKind {
|
||||
/// What to do when the radius is too large for the geometry around the edges.
|
||||
#[serde(default, skip_serializing_if = "FilletFit::is_exact")]
|
||||
fit: FilletFit,
|
||||
/// What fills the corners where three blended edges meet: the rolling ball's sphere
|
||||
/// (default) or a G2 patch repeating each blend up to the second order.
|
||||
#[serde(default, skip_serializing_if = "FilletCorner::is_rolling")]
|
||||
corner: FilletCorner,
|
||||
},
|
||||
Chamfer {
|
||||
edges: Vec<Position>,
|
||||
@@ -662,12 +658,6 @@ pub enum FeatureKind {
|
||||
Hole {
|
||||
#[walk(pick_if = points.is_none())]
|
||||
position: FacePick,
|
||||
/// The position as length expressions, when it was given that way (#1678): the hole is
|
||||
/// drilled where they evaluate, and follows the parameters. `position` keeps the point
|
||||
/// they gave when the hole was made.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", with = "opt_point_expr")]
|
||||
#[walk(placement)]
|
||||
at: Option<PointExpr>,
|
||||
/// Drilling direction (into the material).
|
||||
direction: Dir,
|
||||
#[walk(length = "Diameter")]
|
||||
@@ -1321,10 +1311,6 @@ pub enum FeatureKind {
|
||||
/// sketch curves: walls only, no caps.
|
||||
SurfaceLoft {
|
||||
sections: Vec<SheetSection>,
|
||||
#[serde(default = "loft_plain_continuity", skip_serializing_if = "loft_continuity_is_plain")]
|
||||
continuity: [Continuity; 2],
|
||||
#[serde(default, skip_serializing_if = "loft_crown_is_plain")]
|
||||
crown: [f64; 2],
|
||||
},
|
||||
/// The faces at `faces` copied out at a signed `distance` along their normals as a new
|
||||
/// surface body (0 copies them); `chain` takes each pick's whole smooth chain of faces;
|
||||
@@ -1505,23 +1491,6 @@ pub enum FeatureKind {
|
||||
},
|
||||
}
|
||||
|
||||
/// What fills the corner where three blended edges meet.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
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`).
|
||||
G2,
|
||||
}
|
||||
|
||||
impl FilletCorner {
|
||||
pub fn is_rolling(&self) -> bool {
|
||||
matches!(self, FilletCorner::Rolling)
|
||||
}
|
||||
}
|
||||
|
||||
/// How Extend continues a surface past its edges.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -1765,28 +1734,6 @@ pub struct SheetSection {
|
||||
pub profiles: Option<ProfileSel>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub curves: Vec<String>,
|
||||
/// A section picked as an edge chain of a body instead of a sketch: `edges` are points on the
|
||||
/// chain, and the face the chain bounds is the surface the loft leaves there.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub body: Option<BodyName>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub edges: Vec<Position>,
|
||||
}
|
||||
|
||||
/// A loft's continuity where a design does not say: both ends G0, the loft of old, which only
|
||||
/// passes through its sections.
|
||||
fn loft_plain_continuity() -> [Continuity; 2] {
|
||||
[Continuity::G0, Continuity::G0]
|
||||
}
|
||||
|
||||
/// A loft's continuity is plain when it only passes through its sections: both ends G0.
|
||||
fn loft_continuity_is_plain(c: &[Continuity; 2]) -> bool {
|
||||
*c == [Continuity::G0, Continuity::G0]
|
||||
}
|
||||
|
||||
/// A loft's crown is plain when neither end is filled out.
|
||||
fn loft_crown_is_plain(c: &[f64; 2]) -> bool {
|
||||
c.iter().all(|v| *v == 0.0)
|
||||
}
|
||||
|
||||
/// Coil cross-sections.
|
||||
@@ -1941,22 +1888,6 @@ mod point_expr {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`point_expr`] for an optional point.
|
||||
mod opt_point_expr {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Wrap(#[serde(with = "super::point_expr")] super::PointExpr);
|
||||
|
||||
pub fn serialize<S: Serializer>(p: &Option<super::PointExpr>, s: S) -> Result<S::Ok, S::Error> {
|
||||
p.as_ref().map(|p| Wrap(p.clone())).serialize(s)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<super::PointExpr>, D::Error> {
|
||||
Ok(Option::<Wrap>::deserialize(d)?.map(|w| w.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl FeatureKind {
|
||||
/// A sheet metal feature (its result depends on the sheet metal rules).
|
||||
pub fn is_plastic(&self) -> bool {
|
||||
|
||||
+20
-221
@@ -209,12 +209,6 @@ const ISO_COARSE: [(f64, f64); 22] = [
|
||||
(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();
|
||||
@@ -227,7 +221,7 @@ pub fn parse_metric_thread(s: &str) -> Option<(f64, f64)> {
|
||||
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))
|
||||
(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
|
||||
@@ -247,12 +241,6 @@ fn format_thread(d: f64, p: f64) -> String {
|
||||
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<String> {
|
||||
thread_on(st, 0, p, None, None).map(|t| t.designation)
|
||||
}
|
||||
|
||||
/// A cosmetic thread on the cylindrical face at `p`.
|
||||
fn thread_on(st: &ModelState, feature: u64, p: Vec3, designation: Option<&str>, length: Option<f64>) -> Result<ThreadInfo> {
|
||||
let (body, cyl) = st
|
||||
@@ -1183,8 +1171,7 @@ impl Model {
|
||||
b.made = crate::lineage::Made::Before;
|
||||
}
|
||||
let mut warning = 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).
|
||||
// Face references by name: move each face point onto its named face.
|
||||
let renamed;
|
||||
// Cylindrical emboss resolves its named face in the selected body's frame
|
||||
// and certifies an analytic anchor; mesh projection here would undo that.
|
||||
@@ -1204,7 +1191,7 @@ impl Model {
|
||||
if n.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match crate::name_lookup::locate_face_on_body(&fst, f.kind.face_body(), n, *p) {
|
||||
match crate::naming::locate_face(&fst, n, *p) {
|
||||
Some(hit) => {
|
||||
if let Some(note) = hit.note(n) {
|
||||
notes.push(note);
|
||||
@@ -1942,39 +1929,6 @@ fn extend_for_coplanar(st: &ModelState, plane: &Plane, r: &Region2, lo: f64, hi:
|
||||
(lo2, hi2)
|
||||
}
|
||||
|
||||
/// 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<Arc<Mesh>> = 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;
|
||||
@@ -2345,8 +2299,8 @@ fn sketch_hole_dir(st: &ModelState, spots: &[Vec3], n: Vec3) -> Vec3 {
|
||||
|
||||
/// Where a hole feature drills (each on the surface) and in which direction: at its sketch
|
||||
/// points perpendicular to the sketch (into the material), else at its position.
|
||||
fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
|
||||
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
|
||||
fn hole_spots(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
|
||||
let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
|
||||
let (spots, dir) = match points {
|
||||
Some(sp) => {
|
||||
let ss =
|
||||
@@ -2362,7 +2316,7 @@ fn hole_spots(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> R
|
||||
}
|
||||
None => {
|
||||
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
|
||||
let at = hole_on_surface(st, hole_position(vals, position, at)?, dir);
|
||||
let at = hole_on_surface(st, position.0, dir);
|
||||
let dir = hole_dir_into_face(st, at, dir);
|
||||
return Ok((vec![hole_on_surface(st, at, dir)], dir));
|
||||
}
|
||||
@@ -2396,8 +2350,8 @@ fn hole_depth_to(st: &ModelState, at: &Vec3, dir: Vec3, to: &Option<Vec3>, depth
|
||||
}
|
||||
|
||||
/// A hole's spots as given (not yet moved onto the surface) and its direction.
|
||||
fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
|
||||
let FeatureKind::Hole { position, at, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
|
||||
fn hole_spots_raw(st: &ModelState, f: &Feature) -> Result<(Vec<Vec3>, Vec3)> {
|
||||
let FeatureKind::Hole { position, direction, points, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
|
||||
match points {
|
||||
Some(sp) => {
|
||||
let ss = st.sketch(sp.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", sp.sketch)))?;
|
||||
@@ -2409,29 +2363,16 @@ fn hole_spots_raw(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature)
|
||||
}
|
||||
None => {
|
||||
let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
|
||||
let p = hole_position(vals, position, at)?;
|
||||
Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir), dir)))
|
||||
Ok((vec![position.0], hole_dir_into_face(st, hole_on_surface(st, position.0, dir), dir)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a hole placed by position is drilled: its `at` expressions evaluated, so it follows the
|
||||
/// parameters (#1678), else the point it was given.
|
||||
fn hole_position(vals: &BTreeMap<String, Value>, position: &crate::FacePick, at: &Option<crate::PointExpr>) -> Result<Vec3> {
|
||||
let Some([x, y, z]) = at else { return Ok(position.0) };
|
||||
let p =
|
||||
Vec3::new(Document::eval_in(vals, x, Kind::Length)?, Document::eval_in(vals, y, Kind::Length)?, Document::eval_in(vals, z, Kind::Length)?);
|
||||
if ![p.x, p.y, p.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) {
|
||||
return Err(DocError::Invalid("the hole's position is out of range".into()));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// The cutting tools of a hole feature at every spot, each with its exact geometry when it is a
|
||||
/// straight cylinder (see [`hole_tools_and_prisms`]).
|
||||
fn hole_feature_tools(vals: &BTreeMap<String, Value>, st: &ModelState, f: &Feature) -> Result<Vec<(Traced, Option<more::PrimitivePrism>)>> {
|
||||
let FeatureKind::Hole { diameter, depth, hole, to, .. } = &f.kind else { return Err(DocError::Invalid("not a hole".into())) };
|
||||
let (spots, dir) = hole_spots(vals, st, f)?;
|
||||
let (spots, dir) = hole_spots(st, f)?;
|
||||
if spots.is_empty() || spots.len() > 10_000 {
|
||||
return Err(DocError::Invalid("a hole needs 1…10000 points".into()));
|
||||
}
|
||||
@@ -2873,40 +2814,16 @@ fn feature_tools_with_constructor(
|
||||
// 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() };
|
||||
// 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 { (from - len, from) } else { (from, from + len) };
|
||||
let (l2, h2) = extend_for_coplanar(st, &ss.plane, r, lo, hi, *operation, &crate::plain(targets));
|
||||
let (mut a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) };
|
||||
// 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, &crate::plain(targets)) {
|
||||
a = 0.0;
|
||||
}
|
||||
}
|
||||
let (a, b) = if sign < 0.0 { (from - h2, from - l2) } else { (l2 - from, h2 - from) };
|
||||
// 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 foot = if a >= 0.0 && on_face { TAPER_FOOT.min((b - a) * 0.01) } else { 0.0 };
|
||||
let body = kernel::extrude_tapered_between(&start_plane, r, a, b, foot, sign, taper)?;
|
||||
growth = growth.max(a.abs().max(b.abs()) * taper.tan().abs());
|
||||
Ok(roles.tool(body, None))
|
||||
Ok(crate::lineage::ProfileRoles { sketch: Some(&ss), region: Some(r), caps: caps.clone() }.tool(body, None))
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
// Profiles apart by more than the tools grow (the letters of a text): the tools
|
||||
@@ -3167,9 +3084,6 @@ fn feature_tools_with_constructor(
|
||||
{
|
||||
return build_curved(®ions, -axis_w, tb);
|
||||
}
|
||||
// A new body is final: its planar faces come out whole. A boolean's tool is not
|
||||
// healed (the boolean heals its result).
|
||||
let revolve = if operation == Operation::NewBody { kernel::revolve_whole } else { kernel::revolve };
|
||||
if *convention == crate::RevolveConvention::SketchNormal {
|
||||
let mut out = Vec::new();
|
||||
for (region, region_extent) in regions.iter().zip(®ion_extents) {
|
||||
@@ -3178,7 +3092,7 @@ fn feature_tools_with_constructor(
|
||||
out.extend(build_curved(std::slice::from_ref(region), rotation_axis, tb)?);
|
||||
continue;
|
||||
}
|
||||
let bodies = revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?;
|
||||
let bodies = kernel::revolve(&ss.plane, std::slice::from_ref(region), o, d, region_extent.sweep)?;
|
||||
let m = crate::rigid(Vec3::ZERO, origin_w, rotation_axis, region_extent.start);
|
||||
for body in bodies {
|
||||
out.push(if region_extent.start.abs() < 1e-12 {
|
||||
@@ -3190,7 +3104,7 @@ fn feature_tools_with_constructor(
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let bodies = revolve(&ss.plane, ®ions, o, d, ang)?;
|
||||
let bodies = kernel::revolve(&ss.plane, ®ions, o, d, ang)?;
|
||||
if start.abs() < 1e-12 {
|
||||
return Ok(regions.iter().zip(bodies).map(|(r, body)| tool(r, body, None)).collect());
|
||||
}
|
||||
@@ -3840,7 +3754,7 @@ fn replay(
|
||||
// A hole is drilled again at each copy of its spot (found on the surface there), so
|
||||
// a blind hole's depth counts from the face at the copy, not from the bottom of the
|
||||
// original hole under the original spot.
|
||||
let (spots, dir) = hole_spots_raw(vals, st, src)?;
|
||||
let (spots, dir) = hole_spots_raw(st, src)?;
|
||||
for (k, m) in mats.iter().enumerate() {
|
||||
let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;
|
||||
for p in &spots {
|
||||
@@ -4293,7 +4207,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
|
||||
apply_traced(st, f, tools, *operation, &crate::plain(targets))
|
||||
}
|
||||
FeatureKind::Hole { thread, diameter, .. } => {
|
||||
let (spots, dir) = hole_spots(vals, st, f)?;
|
||||
let (spots, dir) = hole_spots(st, f)?;
|
||||
let tools = hole_feature_tools(vals, st, f)?;
|
||||
let handled = sheet_hole_cut(st, f, &tools, warning)?;
|
||||
let tools: Vec<Traced> = tools.into_iter().map(|(tool, _)| tool).collect();
|
||||
@@ -4495,35 +4409,31 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
|
||||
FeatureKind::Split { body, plane, tool, sketch, line } => {
|
||||
let i = st.bodies.iter().position(|b| &b.name == body).ok_or_else(|| DocError::Unknown(format!("body `{body}`")))?;
|
||||
let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Unknown(format!("body `{body}`"))) };
|
||||
let input = mb.traced();
|
||||
let parts = match tool {
|
||||
// A sketch line: the plane through it along the sketch's normal.
|
||||
_ if sketch.is_some() || line.is_some() => {
|
||||
let (Some(sketch), Some(line)) = (sketch, line) else {
|
||||
return Err(DocError::Invalid("a sketch line tool needs both its sketch and its line".into()));
|
||||
};
|
||||
split_by_plane_traced(&input, &sketch_line_plane(st, sketch.0, line)?)?
|
||||
kernel::split_by_plane(&mb.body, &sketch_line_plane(st, sketch.0, line)?)?
|
||||
}
|
||||
// A face of a body (its surface extended).
|
||||
Some(t) => {
|
||||
let tb = st.body(&t.body).ok_or_else(|| DocError::Unknown(format!("body `{}`", t.body)))?;
|
||||
let face = crate::appearance::face_index_at(tb, t.point.0)
|
||||
.ok_or_else(|| DocError::Invalid(format!("no face of `{}` at the tool point", t.body)))?;
|
||||
// The pieces keep the planar roles of the faces they share with the body (#565).
|
||||
kernel::split_body(&mb.body, &kernel::SplitTool::Face { body: &tb.body, face })?
|
||||
.into_iter()
|
||||
.map(|part| Ok(Traced::step(part.with_preserved_planar_sources(&mb.body)?, &[&input])))
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
}
|
||||
None => {
|
||||
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
|
||||
split_by_plane_traced(&input, &pl)?
|
||||
kernel::split_by_plane(&mb.body, &pl)?
|
||||
}
|
||||
};
|
||||
if parts.len() < 2 {
|
||||
return Err(DocError::Invalid("the tool does not split the body".into()));
|
||||
}
|
||||
let mut it = parts.into_iter();
|
||||
let input = mb.traced();
|
||||
let mut it = parts.into_iter().map(|part| Traced::step(part, &[&input]));
|
||||
if let (Some(first), Some(slot)) = (it.next(), st.bodies.get_mut(i)) {
|
||||
*slot = ModelBody::traced_new(mb.name.clone(), first, mb.feature);
|
||||
}
|
||||
@@ -4640,16 +4550,8 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
|
||||
};
|
||||
st.blend_edges.insert(f.id, edges.clone());
|
||||
let input = mb.traced();
|
||||
// A G2 corner is built by the corner construction alone, for a constant radius: any
|
||||
// other style (or a fitted radius) has no corner patch to repeat.
|
||||
if let FeatureKind::Fillet { corner: crate::FilletCorner::G2, style, fit, .. } = &f.kind
|
||||
&& (!matches!(style, crate::FilletStyle::Constant) || !matches!(fit, crate::FilletFit::Exact))
|
||||
{
|
||||
return Err(DocError::Invalid("a G2 corner is built for a constant-radius fillet (type: constant, fit: exact) only".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),
|
||||
FeatureKind::Fillet { style: crate::FilletStyle::Chord, .. } => (kernel::fillet_chord(&mb.body, &edges, r)?, input),
|
||||
FeatureKind::Fillet { style: crate::FilletStyle::Variable { radius2, start, mid, smooth }, .. } => {
|
||||
@@ -5335,7 +5237,6 @@ mod chain_tests {
|
||||
body: None,
|
||||
style: crate::FilletStyle::Constant,
|
||||
fit: Default::default(),
|
||||
corner: Default::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -5380,23 +5281,6 @@ mod body_name_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn split_by_plane_traced(input: &Traced, plane: &Plane) -> Result<Vec<Traced>> {
|
||||
let mut parts = Vec::new();
|
||||
for positive in [true, false] {
|
||||
let (part, tool) = kernel::half_space(&input.body, plane, positive)?;
|
||||
let Some(part) = part else { continue };
|
||||
// The box's cap in the plane: its start cap on the positive side, its end cap on the other.
|
||||
let section = Some("section".to_string());
|
||||
let caps = if positive { [section, None] } else { [None, section] };
|
||||
let tool = crate::lineage::ProfileRoles { sketch: None, region: None, caps }.tool(tool, None);
|
||||
parts.push(Traced::step(part, &[input, &tool]));
|
||||
}
|
||||
Ok(parts)
|
||||
}
|
||||
|
||||
/// The plane a straight sketch line sweeps along its sketch's normal: through the line, its x
|
||||
/// along the line and its y along the normal (a Split Body tool, #1552).
|
||||
pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result<Plane> {
|
||||
@@ -5410,88 +5294,3 @@ pub fn sketch_line_plane(st: &ModelState, sketch: u64, line: &str) -> Result<Pla
|
||||
let x = (wb - wa).normalized().ok_or_else(|| DocError::Invalid(format!("`{line}` has no length")))?;
|
||||
Ok(Plane { origin: wa, x, y: ss.plane.normal() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod named_face_lookup_tests {
|
||||
use super::*;
|
||||
use crate::naming::FaceHit;
|
||||
|
||||
/// A row of `n` 10 mm cubes `Part0`, `Part1`… 20 mm apart along x, without history: their
|
||||
/// faces are named from geometry, which meshes them.
|
||||
fn parts(n: usize) -> ModelState {
|
||||
let mut st = ModelState::default();
|
||||
for i in 0..n {
|
||||
let x = 20.0 * i as f64;
|
||||
let cube = kernel::box_solid(Vec3::new(x, 0.0, 0.0), Vec3::new(x + 10.0, 10.0, 10.0)).unwrap();
|
||||
st.bodies.push(ModelBody::new(format!("Part{i}"), cube, 1));
|
||||
}
|
||||
st
|
||||
}
|
||||
|
||||
/// The name of the face of `body` at `p`.
|
||||
fn name_at(st: &ModelState, body: &str, p: Vec3) -> String {
|
||||
let b = st.body(body).unwrap();
|
||||
let face = crate::appearance::face_index_at(b, p).unwrap();
|
||||
crate::naming::face_names(b)[face].clone()
|
||||
}
|
||||
|
||||
/// Everything a lookup found, to compare two lookups.
|
||||
fn found(hit: Option<FaceHit>) -> String {
|
||||
format!("{hit:?}")
|
||||
}
|
||||
|
||||
/// A shell late in a long timeline spent seconds meshing every body of the model to find its
|
||||
/// face by name (#287). A feature that names its body finds the face there without naming
|
||||
/// the other bodies, and finds what looking over every body finds.
|
||||
#[test]
|
||||
fn a_face_is_found_on_the_body_the_feature_names_without_meshing_the_others() {
|
||||
let st = parts(12);
|
||||
let top = Vec3::new(145.0, 5.0, 10.0);
|
||||
let name = name_at(&st, "Part7", top);
|
||||
let hit = crate::name_lookup::locate_face_on_body(&st, Some("Part7"), &name, top);
|
||||
for b in st.bodies.iter().filter(|b| b.name != "Part7") {
|
||||
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!(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()));
|
||||
}
|
||||
|
||||
/// A name the named body has no face of (it moved to another body: a combine took the face),
|
||||
/// a body that is not there, no body, a name saved before format 14 or a name no face has:
|
||||
/// looked for over every body, as without a body.
|
||||
#[test]
|
||||
fn a_name_not_on_the_named_body_is_looked_for_over_every_body() {
|
||||
let st = parts(4);
|
||||
let top = Vec3::new(45.0, 5.0, 10.0);
|
||||
let name = name_at(&st, "Part2", top);
|
||||
for name in [name.clone(), format!("{}{name}", crate::naming::LEGACY_MARK), "Part2:face:99".into()] {
|
||||
let everywhere = found(crate::naming::locate_face(&st, &name, top));
|
||||
for body in [Some("Part1"), Some("Part2"), Some("Nope"), None] {
|
||||
assert_eq!(found(crate::name_lookup::locate_face_on_body(&st, body, &name, top)), everywhere, "{name} on {body:?}");
|
||||
}
|
||||
}
|
||||
let moved = crate::name_lookup::locate_face_on_body(&st, Some("Part1"), &name, top).unwrap();
|
||||
assert_eq!((moved.body, moved.split), (2, false));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn the_same_face_on_a_copy_is_not_a_piece_of_the_named_bodys_face() {
|
||||
let mut st = parts(2);
|
||||
let source = st.bodies[0].clone();
|
||||
st.bodies[1].names = crate::naming::NameCell::same(&source);
|
||||
let top = Vec3::new(25.0, 5.0, 10.0);
|
||||
let name = name_at(&st, "Part1", top);
|
||||
assert_eq!(name, name_at(&st, "Part0", Vec3::new(5.0, 5.0, 10.0)));
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! `surface_offset`, `surface_ruled`, `surface_untrim`).
|
||||
|
||||
use super::*;
|
||||
use crate::{RuledCorners, RuledMode, SheetSection};
|
||||
use crate::{RuledCorners, RuledMode};
|
||||
use solidcraft_geom::Seg2;
|
||||
|
||||
pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st: &mut ModelState, warning: &mut Option<String>) -> Result<()> {
|
||||
@@ -313,13 +313,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,
|
||||
push_sheet(st, f, traced);
|
||||
Ok(())
|
||||
}
|
||||
FeatureKind::SurfaceLoft { sections, continuity, crown } => {
|
||||
// A loft with edge chains for sections, or one that has to leave its ends a particular
|
||||
// way, is built through `loft_blend` from the frames of every section; the plain one
|
||||
// (sketch chains only, both ends G0) is the loft of old.
|
||||
if *continuity != [kernel::Continuity::G0, kernel::Continuity::G0] || sections.iter().any(|s| s.body.is_some()) {
|
||||
return loft_blend(st, f, sections, *continuity, *crown, doc);
|
||||
}
|
||||
FeatureKind::SurfaceLoft { sections } => {
|
||||
let mut secs = Vec::with_capacity(sections.len());
|
||||
let mut sketches = Vec::with_capacity(sections.len());
|
||||
for sec in sections {
|
||||
@@ -559,118 +553,3 @@ fn curve_chains(ss: &SolvedSketch, ids: &[String]) -> Result<Vec<Vec<Seg2>>> {
|
||||
}
|
||||
Ok(chains)
|
||||
}
|
||||
|
||||
/// A multi-section blend: every section as frames, the body ones read off the face their edge
|
||||
/// chain bounds, and the first and last leaving with `continuity` where the caller asks for it.
|
||||
fn loft_blend(
|
||||
st: &mut ModelState,
|
||||
f: &Feature,
|
||||
sections: &[SheetSection],
|
||||
continuity: [kernel::Continuity; 2],
|
||||
crown: [f64; 2],
|
||||
doc: &Document,
|
||||
) -> Result<()> {
|
||||
/// One section: a chain of sketch curves in its plane, or a body's edge chain.
|
||||
enum Piece {
|
||||
Sketch(solidcraft_geom::Plane, Vec<solidcraft_geom::Seg2>),
|
||||
Body(String, Vec<solidcraft_geom::Vec3>),
|
||||
}
|
||||
let mut pieces = Vec::with_capacity(sections.len());
|
||||
let mut centres = Vec::with_capacity(sections.len());
|
||||
for sec in sections {
|
||||
if let Some(name) = sec.body.as_deref() {
|
||||
if sec.edges.is_empty() {
|
||||
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));
|
||||
pieces.push(Piece::Body(name.to_string(), crate::plain(&sec.edges)));
|
||||
continue;
|
||||
}
|
||||
let ss = sketch_in_feature_frame(
|
||||
doc,
|
||||
st.sketch(sec.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {} (it must come earlier in the timeline)", sec.sketch)))?,
|
||||
f.component,
|
||||
)?;
|
||||
let profiles = match (&sec.profiles, sec.curves.is_empty()) {
|
||||
(None, true) => Some(&ProfileSel::All),
|
||||
(p, _) => p.as_ref(),
|
||||
};
|
||||
let mut chains = sheet_chains(&ss, profiles, &sec.curves)?.into_iter();
|
||||
let (Some(chain), None) = (chains.next(), chains.next()) else {
|
||||
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<Vec2> = 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);
|
||||
centres.push(centre);
|
||||
pieces.push(Piece::Sketch(ss.plane, chain));
|
||||
}
|
||||
// Each section leaves towards the one after it; the last one leaves back into the blend.
|
||||
let stations = BLEND_STATIONS;
|
||||
let last = pieces.len().saturating_sub(1);
|
||||
let mut frames = Vec::with_capacity(pieces.len());
|
||||
for (i, piece) in pieces.iter().enumerate() {
|
||||
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,
|
||||
};
|
||||
match piece {
|
||||
Piece::Body(name, edges) => {
|
||||
let b = st.body(name).ok_or_else(|| DocError::Unknown(format!("body `{name}`")))?.body.clone();
|
||||
frames.push(kernel::loft_blend::section_frames(&b, edges, leave, stations)?);
|
||||
}
|
||||
Piece::Sketch(plane, chain) => frames.push(chain_frames(plane, chain, leave, stations)),
|
||||
}
|
||||
}
|
||||
let body = kernel::loft_blend(&frames, continuity, crown, stations)?;
|
||||
let name = new_name(st, f, 0);
|
||||
st.bodies.push(ModelBody::new(name, body, f.id));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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,
|
||||
stations: usize,
|
||||
) -> Vec<kernel::Frame> {
|
||||
let mut pts: Vec<Vec2> = Vec::new();
|
||||
for seg in chain {
|
||||
for p in seg.polyline(1e-2) {
|
||||
if pts.last().is_none_or(|l: &Vec2| (*l - p).len() > 1e-12) {
|
||||
pts.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
if pts.len() < 2 || stations < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
let total: f64 = pts.windows(2).map(|w| (w[1] - w[0]).len()).sum();
|
||||
if !(total > 1e-12) {
|
||||
return Vec::new();
|
||||
}
|
||||
let step = total / (stations - 1) as f64;
|
||||
let (mut walked, mut k) = (0.0f64, 0usize);
|
||||
let mut out = Vec::with_capacity(stations);
|
||||
for i in 0..stations {
|
||||
let want = step * i as f64;
|
||||
while k + 1 < pts.len() && walked + (pts[k + 1] - pts[k]).len() < want {
|
||||
walked += (pts[k + 1] - pts[k]).len();
|
||||
k += 1;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -53,26 +53,6 @@ impl FeatureKind {
|
||||
v
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn face_body(&self) -> Option<&str> {
|
||||
match self {
|
||||
FeatureKind::Shell { body, .. }
|
||||
| FeatureKind::Draft { body, .. }
|
||||
| FeatureKind::SplitFace { body, .. }
|
||||
| FeatureKind::OffsetFace { body, .. }
|
||||
| FeatureKind::DeleteFace { body, .. }
|
||||
| FeatureKind::ReplaceFace { body, .. }
|
||||
| FeatureKind::SurfaceOffset { body, .. }
|
||||
| FeatureKind::Boss { body, .. }
|
||||
| FeatureKind::SnapFit { body, .. }
|
||||
| FeatureKind::Rest { body, .. } => body.as_deref(),
|
||||
FeatureKind::SheetConvert { body, .. } | FeatureKind::SurfaceRuled { body, .. } => Some(body.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The feature's profile selections, each with its sketch.
|
||||
pub fn profile_sels_mut(&mut self) -> Vec<(u64, &mut ProfileSel)> {
|
||||
let mut v = Vec::new();
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
//! A motion link can carry a `cam` coupling (`joint.cam`): the cam's `profile` (a sketch's closed
|
||||
//! profile by its outer loop's curve ids, or picked edges of the cam's bodies with their names),
|
||||
//! the `follower` (`knife`, `roller` with a `radius`, or `flat`), an optional `tip` (a joint origin
|
||||
//! where the follower touches) and `reverse` (the side it rides from). The link then also saves
|
||||
//! `lift`, the follower's values over one turn of the cam, worked out from the profile again
|
||||
//! whenever the design changes. Older designs need no transformation: a link without them is a
|
||||
//! plain motion link, as it always was; 0.13.x asks for an update instead of reading a cam's
|
||||
//! follower as a plain link of ratio 1.
|
||||
@@ -1,7 +0,0 @@
|
||||
//! The Class-A surface pass also lets a `Fillet` carry `corner` (`rolling`, the default and what
|
||||
//! every older design meant, or `g2`: a patch repeating each blend's surface up to the second
|
||||
//! order) and a `SurfaceLoft` carry `continuity` and `crown` and body edge-chain `sections` (a
|
||||
//! section picked as a `body` with `edges` instead of a `sketch`). A design without them saves as
|
||||
//! it always did — a loft without `continuity` reads and writes as `[g0, g0]`, the plain loft it
|
||||
//! always was — so older designs need no transformation; 0.13.x asks for an update instead of
|
||||
//! meeting a feature it can't read or dropping a corner style it does not round.
|
||||
@@ -1,5 +0,0 @@
|
||||
//! A Hole placed by position can keep that position as length expressions (`at`: `[x, y, z]`,
|
||||
//! numbers as numbers, expressions as strings), and is drilled where they evaluate, so it follows
|
||||
//! the design's parameters (#1678). `position` still holds the point it was made at. Older designs
|
||||
//! need no transformation: a hole without `at` is drilled at `position` as before; 0.13.x asks for
|
||||
//! an update instead of drilling a moved hole at its old point.
|
||||
+16
-61
@@ -1,8 +1,8 @@
|
||||
//! Joints between occurrences: joint origins (snap frames on component geometry, re-found on
|
||||
//! every solve so they follow edits), joints (rigid, revolute, slider, cylindrical, pin-slot,
|
||||
//! planar, ball) with their motion values and limits, motion links (gears, racks and screws are
|
||||
//! links whose ratio comes from radii or a pitch; a cam's follower follows a table worked out from
|
||||
//! its profile, `joints_cam.rs`), and the solver that places occurrences from the joint graph.
|
||||
//! links whose ratio comes from radii or a pitch), and the solver that places occurrences from
|
||||
//! the joint graph.
|
||||
//!
|
||||
//! A joint makes B's joint frame coincide with A's frame moved by the joint's motion:
|
||||
//! `T_B · F_b = T_A · F_a · M(q) · Flip`, so `T_B = T_A · F_a · M(q) · Flip · F_b⁻¹`, where `T`
|
||||
@@ -140,8 +140,7 @@ pub struct Joint {
|
||||
pub suppressed: bool,
|
||||
}
|
||||
|
||||
/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset, or for a
|
||||
/// cam, its `lift` table at a's value + offset.
|
||||
/// Value of joint `b` (index `ib`) = ratio · value of joint `a` (index `ia`) + offset.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MotionLink {
|
||||
pub a: u64,
|
||||
@@ -153,29 +152,11 @@ pub struct MotionLink {
|
||||
pub ratio: f64,
|
||||
#[serde(default)]
|
||||
pub offset: f64,
|
||||
/// Gears, a rack and pinion, a screw or a cam: what the ratio (or a cam's table) comes from.
|
||||
/// It is worked out from it again whenever the design changes (`coupling_values`), so it
|
||||
/// follows the radii, the pitch and the cam's profile; the last one worked out is kept in
|
||||
/// `ratio` and `lift`.
|
||||
/// Gears, a rack and pinion or a screw: what the ratio comes from. The ratio is worked out
|
||||
/// from it again whenever the design changes (`coupling_ratio`), so it follows the radii and
|
||||
/// the pitch; the last one worked out is kept in `ratio`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub coupling: Option<Coupling>,
|
||||
/// A cam's follower values over one turn of a (`cam::CAM_SAMPLES` of them, in b's units, the
|
||||
/// offset left out); empty for every other link.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub lift: Vec<f64>,
|
||||
}
|
||||
|
||||
impl MotionLink {
|
||||
/// b's value for a's value `x` (before b's limits). A cam's table that is not whole (a
|
||||
/// hand-edited file) gives no value, so b keeps where it is; a table on any other link is
|
||||
/// not read.
|
||||
pub fn follow(&self, x: f64) -> f64 {
|
||||
match &self.coupling {
|
||||
Some(Coupling::Cam(_)) if self.lift.len() == cam::CAM_SAMPLES => cam::lift_at(&self.lift, x) + self.offset,
|
||||
Some(Coupling::Cam(_)) => f64::NAN,
|
||||
_ => self.ratio * x + self.offset,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A length a coupling's ratio comes from: millimetres, an expression over the design's
|
||||
@@ -218,22 +199,14 @@ pub enum Coupling {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
reverse: bool,
|
||||
},
|
||||
/// A cam on a revolute joint (a) and its follower (b, a slider or a revolute): b rides the
|
||||
/// cam's profile (`joints_cam.rs`).
|
||||
Cam(cam::Cam),
|
||||
}
|
||||
|
||||
impl Coupling {
|
||||
/// The lengths the ratio comes from: a's gear and b's, the pinion's radius, the pitch, or a
|
||||
/// cam's roller radius.
|
||||
/// The lengths the ratio comes from: a's gear and b's, or the pinion's radius or the pitch.
|
||||
pub fn sizes(&self) -> Vec<&Size> {
|
||||
match self {
|
||||
Coupling::Gear { ra, rb, .. } => vec![ra, rb],
|
||||
Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s],
|
||||
Coupling::Cam(c) => match &c.follower {
|
||||
cam::Follower::Roller { radius } => vec![radius],
|
||||
_ => Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,10 +214,6 @@ impl Coupling {
|
||||
match self {
|
||||
Coupling::Gear { ra, rb, .. } => vec![ra, rb],
|
||||
Coupling::RackPinion { radius: s, .. } | Coupling::Screw { pitch: s, .. } => vec![s],
|
||||
Coupling::Cam(c) => match &mut c.follower {
|
||||
cam::Follower::Roller { radius } => vec![radius],
|
||||
_ => Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -262,18 +231,14 @@ fn size_of(doc: &Document, st: &ModelState, s: &Size) -> Result<f64> {
|
||||
if v.is_finite() && v > 1e-9 && v <= MAX_SIZE {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err(DocError::Invalid(format!("a gear, rack, screw or roller needs a positive length, not {v}")))
|
||||
Err(DocError::Invalid(format!("a gear, rack or screw needs a positive length, not {v}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// The ratio a link's coupling gives it (b's value per a's, in radians and mm) and a cam's table
|
||||
/// (`MotionLink::lift`; empty for the others), worked out from the geometry and parameters it is
|
||||
/// defined by; `None` for a plain link.
|
||||
pub fn coupling_values(doc: &Document, st: &ModelState, l: &MotionLink) -> Option<Result<(f64, Vec<f64>)>> {
|
||||
l.coupling.as_ref().map(|c| match c {
|
||||
Coupling::Cam(c) => cam::table(doc, st, l, c).map(|t| (1.0, t)),
|
||||
c => coupled(doc, st, l, c).map(|r| (r, Vec::new())),
|
||||
})
|
||||
/// The ratio a link's coupling gives it (b's value per a's, in radians and mm), worked out from
|
||||
/// the geometry and parameters it is defined by; `None` for a plain link.
|
||||
pub fn coupling_ratio(doc: &Document, st: &ModelState, l: &MotionLink) -> Option<Result<f64>> {
|
||||
l.coupling.as_ref().map(|c| coupled(doc, st, l, c))
|
||||
}
|
||||
|
||||
fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Result<f64> {
|
||||
@@ -295,8 +260,6 @@ fn coupled(doc: &Document, st: &ModelState, l: &MotionLink, c: &Coupling) -> Res
|
||||
}
|
||||
Coupling::RackPinion { radius, reverse } => Ok(travel(size_of(doc, st, radius)?)? * sign(*reverse)),
|
||||
Coupling::Screw { pitch, reverse } => Ok(travel(size_of(doc, st, pitch)? / std::f64::consts::TAU)? * sign(*reverse)),
|
||||
// A cam's follower follows its table (`coupling_values`), not a ratio.
|
||||
Coupling::Cam(_) => Ok(1.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,11 +491,7 @@ fn apply_links(asm: &Assembly, vals: &mut Values) {
|
||||
let before = linked(vals);
|
||||
for l in &asm.links {
|
||||
let Some(src) = vals.get(&l.a).and_then(|q| q.get(l.ia)).copied() else { continue };
|
||||
let mut next = l.follow(src);
|
||||
// A hand-edited table (or source) that gives no number leaves b where it is.
|
||||
if !next.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let mut next = l.ratio * src + l.offset;
|
||||
if let Some((lo, hi)) = limits.get(&(l.b, l.ib)) {
|
||||
next = next.max(*lo).min(*hi);
|
||||
}
|
||||
@@ -1429,9 +1388,6 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "joints_cam.rs"]
|
||||
pub mod cam;
|
||||
|
||||
#[path = "joints_reach.rs"]
|
||||
mod reach;
|
||||
pub use reach::{REACH_TOL, Reach, Reached, reach};
|
||||
@@ -1469,8 +1425,7 @@ mod tests {
|
||||
suppressed: false,
|
||||
})
|
||||
.collect();
|
||||
let links =
|
||||
(1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None, lift: Vec::new() }).collect();
|
||||
let links = (1..n).rev().map(|a| MotionLink { a, ia: 0, b: a + 1, ib: 0, ratio: 2.0, offset: 0.0, coupling: None }).collect();
|
||||
Assembly { joints, links, ..Assembly::default() }
|
||||
}
|
||||
|
||||
@@ -1522,8 +1477,8 @@ mod tests {
|
||||
}
|
||||
let st = ModelState::default();
|
||||
let ratio = |a: u64, b: u64, c: Coupling| {
|
||||
let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c), lift: Vec::new() };
|
||||
coupling_values(&doc, &st, &l).map(|r| r.map(|(ratio, _)| ratio).map_err(|e| e.to_string()))
|
||||
let l = MotionLink { a, ia: 0, b, ib: 0, ratio: 0.0, offset: 0.0, coupling: Some(c) };
|
||||
coupling_ratio(&doc, &st, &l).map(|r| r.map_err(|e| e.to_string()))
|
||||
};
|
||||
let len = Size::Length;
|
||||
assert_eq!(ratio(1, 2, Coupling::Gear { ra: len(10.0), rb: len(40.0), internal: false, reverse: false }), Some(Ok(-0.25)));
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -58,9 +58,9 @@ pub use assembly::{
|
||||
pub use document::*;
|
||||
pub use eval::{
|
||||
EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for,
|
||||
edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, 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, through_all_distance, world_state, world_state_reusing,
|
||||
edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, 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,
|
||||
through_all_distance, world_state, world_state_reusing,
|
||||
};
|
||||
pub use expr::Expr;
|
||||
pub use names::{BodyName, FeatureName, SketchId};
|
||||
|
||||
@@ -271,25 +271,6 @@ pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option<FaceHit> {
|
||||
locate_in(st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()), name, p)
|
||||
}
|
||||
|
||||
/// [`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<FaceHit> {
|
||||
if legacy_name(name).is_none()
|
||||
&& 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);
|
||||
}
|
||||
locate_face(st, name, p)
|
||||
}
|
||||
|
||||
/// [`locate_face`] among `bodies` (with their indices).
|
||||
fn locate_in<'a>(bodies: impl Iterator<Item = (usize, &'a ModelBody)>, name: &str, p: Vec3) -> Option<FaceHit> {
|
||||
if let Some(old) = legacy_name(name) {
|
||||
|
||||
+58
-167
@@ -578,22 +578,14 @@ fn rev_edge(e: EdgeSpec) -> EdgeSpec {
|
||||
e.reversed()
|
||||
}
|
||||
|
||||
/// Largest distance between a folded bend edge and the chain standing in for it.
|
||||
/// Largest distance between a folded bend edge and the cubic chain standing in for it.
|
||||
const BEND_CHAIN_TOL: f64 = 1e-7;
|
||||
/// Degree of the pieces of a folded bend edge's chain. Hermite pieces of degree 7 match the
|
||||
/// edge's point and first three derivatives at both ends, so one or two of them follow a helix
|
||||
/// round a whole bend, where cubic pieces (point and tangent) took 32 and more.
|
||||
const BEND_CHAIN_DEGREE: usize = 7;
|
||||
/// Most pieces of a folded bend edge's chain.
|
||||
const BEND_CHAIN_PIECES: usize = 256;
|
||||
/// Most halvings of a bend edge's parameter while fitting its chain.
|
||||
const BEND_CHAIN_DEPTH: usize = 10;
|
||||
|
||||
/// The point at `t` of the Bézier over `c` (de Casteljau).
|
||||
fn bezier_at(c: &[Vec3], t: f64) -> Vec3 {
|
||||
let mut w = c.to_vec();
|
||||
while w.len() > 1 {
|
||||
w = w.windows(2).map(|p| p[0].lerp(p[1], t)).collect();
|
||||
}
|
||||
w.first().copied().unwrap_or(Vec3::ZERO)
|
||||
fn cubic_at(p0: Vec3, c1: Vec3, c2: Vec3, p1: Vec3, t: f64) -> Vec3 {
|
||||
let u = 1.0 - t;
|
||||
p0 * (u * u * u) + c1 * (3.0 * u * u * t) + c2 * (3.0 * u * t * t) + p1 * (t * t * t)
|
||||
}
|
||||
|
||||
fn dedup(p: &[Vec2]) -> Vec<Vec2> {
|
||||
@@ -981,10 +973,8 @@ impl SheetBody {
|
||||
}
|
||||
|
||||
/// A flat point of flange `f`'s bend zone folded onto the bend at height `z` (not clamped
|
||||
/// to the zone), with its first three derivatives along the zone's flat `n` direction and
|
||||
/// its first along `d` (along `d` the bend is straight: the higher ones are zero, and so are
|
||||
/// the mixed ones).
|
||||
fn zone_point(&self, f: &SheetFlange, q: Vec2, z: f64) -> (Vec3, [Vec3; 3], Vec3) {
|
||||
/// to the zone), with its rates of change along the zone's flat `n` and `d` directions.
|
||||
fn zone_point(&self, f: &SheetFlange, q: Vec2, z: f64) -> (Vec3, Vec3, Vec3) {
|
||||
let s = (q - f.p).dot(f.n);
|
||||
let u = (q - f.p).dot(f.d);
|
||||
let neutral = (f.radius + self.k * self.t).max(1e-12);
|
||||
@@ -997,91 +987,58 @@ impl SheetBody {
|
||||
let (sn, cs) = phi.sin_cos();
|
||||
let w = self.world(f.parent);
|
||||
let local = axis_o + v3(f.d) * u + ez * cs + ek * sn;
|
||||
// Each derivative along n turns the last a right angle about the axis and divides it by
|
||||
// the neutral radius.
|
||||
let ds = (ez * -sn + ek * cs) * (1.0 / neutral);
|
||||
let dss = (ez * cs + ek * sn) * (-1.0 / (neutral * neutral));
|
||||
let dsss = ds * (-1.0 / (neutral * neutral));
|
||||
let along_n = [ds, dss, dsss].map(|v| apply_vector(&w, v));
|
||||
(apply_point(&w, local), along_n, apply_vector(&w, v3(f.d)))
|
||||
(apply_point(&w, local), apply_vector(&w, ds), apply_vector(&w, v3(f.d)))
|
||||
}
|
||||
|
||||
/// A flat edge of flange `f`'s bend zone, folded at height `z`, at parameter `t`: the point
|
||||
/// and its first three derivatives.
|
||||
fn zone_edge_at(&self, f: &SheetFlange, e: &Seg2, z: f64, t: f64) -> [Vec3; 4] {
|
||||
let (p, [g1, g2, g3], du) = self.zone_point(f, e.point_at(t), z);
|
||||
let [q1, q2, q3] = match e.derivatives(t, 3).as_deref() {
|
||||
Some(&[q1, q2, q3]) => [q1, q2, q3],
|
||||
_ => [e.derivative(t), Vec2::ZERO, Vec2::ZERO],
|
||||
};
|
||||
let ([s1, s2, s3], [u1, u2, u3]) = ([q1, q2, q3].map(|q| q.dot(f.n)), [q1, q2, q3].map(|q| q.dot(f.d)));
|
||||
// The chain rule (Faà di Bruno) through s(t) along n and u(t) along d.
|
||||
[p, g1 * s1 + du * u1, g2 * (s1 * s1) + g1 * s2 + du * u2, g3 * (s1 * s1 * s1) + g2 * (3.0 * s1 * s2) + g1 * s3 + du * u3]
|
||||
/// and its derivative.
|
||||
fn zone_edge_at(&self, f: &SheetFlange, e: &Seg2, z: f64, t: f64) -> (Vec3, Vec3) {
|
||||
let (p, ds, du) = self.zone_point(f, e.point_at(t), z);
|
||||
let dq = e.derivative(t);
|
||||
(p, ds * dq.dot(f.n) + du * dq.dot(f.d))
|
||||
}
|
||||
|
||||
/// The control points of the Hermite piece of degree 7 of a folded bend edge from `t0` to
|
||||
/// `t1`: it has the edge's point and first three derivatives at both ends. (The k-th
|
||||
/// derivative of a Bézier of degree 7 at its start is 7!/(7 − k)! times the k-th forward
|
||||
/// difference of its first control points, and the edge's k-th derivative scales by
|
||||
/// (t1 − t0)^k to the piece's parameter; at its end the same, backwards.)
|
||||
fn zone_piece(&self, f: &SheetFlange, e: &Seg2, z: f64, t0: f64, t1: f64) -> [Vec3; BEND_CHAIN_DEGREE + 1] {
|
||||
let h = t1 - t0;
|
||||
let ([p0, a1, a2, a3], [p1, b1, b2, b3]) = (self.zone_edge_at(f, e, z, t0), self.zone_edge_at(f, e, z, t1));
|
||||
let (k1, k2, k3) = (h / 7.0, h * h / 42.0, h * h * h / 210.0);
|
||||
[
|
||||
p0,
|
||||
p0 + a1 * k1,
|
||||
p0 + a1 * (2.0 * k1) + a2 * k2,
|
||||
p0 + a1 * (3.0 * k1) + a2 * (3.0 * k2) + a3 * k3,
|
||||
p1 - b1 * (3.0 * k1) + b2 * (3.0 * k2) - b3 * k3,
|
||||
p1 - b1 * (2.0 * k1) + b2 * k2,
|
||||
p1 - b1 * k1,
|
||||
p1,
|
||||
]
|
||||
}
|
||||
|
||||
/// Into how many equal pieces (of its parameter) a bend zone's flat edge is folded, so that
|
||||
/// the Hermite pieces are within [`BEND_CHAIN_TOL`] of the folded edge on both faces. The
|
||||
/// count depends on the flat edge only, so the top face, bottom face and wall of a cut-out
|
||||
/// share one chain per height; and as the pieces are equal, the chain's parameter runs evenly
|
||||
/// with the edge's, and the pieces join with equal derivatives up to the third.
|
||||
fn zone_pieces(&self, f: &SheetFlange, e: &Seg2) -> usize {
|
||||
// The largest distance between the pieces and the folded edge, at points inside each.
|
||||
let worst = |n: usize| {
|
||||
let mut worst = 0.0f64;
|
||||
for k in 0..n {
|
||||
let (t0, t1) = (k as f64 / n as f64, (k + 1) as f64 / n as f64);
|
||||
for z in [0.0, self.t] {
|
||||
let c = self.zone_piece(f, e, z, t0, t1);
|
||||
for j in 1..8 {
|
||||
let t = t0 + (t1 - t0) * j as f64 / 8.0;
|
||||
worst = worst.max(bezier_at(&c, j as f64 / 8.0).dist(self.zone_edge_at(f, e, z, t)[0]));
|
||||
}
|
||||
}
|
||||
/// Where to break a bend zone's flat edge so cubic Hermite pieces follow the folded edge
|
||||
/// to within [`BEND_CHAIN_TOL`] on both faces. The breaks depend on the flat edge only, so
|
||||
/// the top face, bottom face and wall of a cut-out share one chain per height.
|
||||
fn zone_breaks(&self, f: &SheetFlange, e: &Seg2) -> Vec<f64> {
|
||||
let mut out = vec![0.0];
|
||||
let mut todo = vec![(0.0, 1.0, 0usize)];
|
||||
while let Some((t0, t1, depth)) = todo.pop() {
|
||||
let fits = depth >= BEND_CHAIN_DEPTH
|
||||
|| [0.0, self.t].iter().all(|&z| {
|
||||
let h = t1 - t0;
|
||||
let ((p0, d0), (p1, d1)) = (self.zone_edge_at(f, e, z, t0), self.zone_edge_at(f, e, z, t1));
|
||||
let (c1, c2) = (p0 + d0 * (h / 3.0), p1 - d1 * (h / 3.0));
|
||||
[0.25, 0.5, 0.75].iter().all(|&x| cubic_at(p0, c1, c2, p1, x).dist(self.zone_edge_at(f, e, z, t0 + h * x).0) <= BEND_CHAIN_TOL)
|
||||
});
|
||||
if fits {
|
||||
out.push(t1);
|
||||
} else {
|
||||
let m = (t0 + t1) / 2.0;
|
||||
// Depth first, right half last on the stack: breaks come out in order.
|
||||
todo.push((m, t1, depth + 1));
|
||||
todo.push((t0, m, depth + 1));
|
||||
}
|
||||
worst
|
||||
};
|
||||
let mut n = 1;
|
||||
loop {
|
||||
let off = worst(n);
|
||||
if off <= BEND_CHAIN_TOL || !off.is_finite() || n >= BEND_CHAIN_PIECES {
|
||||
return n;
|
||||
}
|
||||
// The distance falls as the eighth power of the pieces' length.
|
||||
let guess = (n as f64 * (off / BEND_CHAIN_TOL).powf(1.0 / 8.0)).ceil();
|
||||
n = (guess as usize).clamp(n + 1, BEND_CHAIN_PIECES);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A bend zone's flat edge folded at height `z`: a chain of Hermite pieces of degree 7.
|
||||
/// A bend zone's flat edge folded at height `z`: a chain of cubic Hermite pieces.
|
||||
fn zone_chain(&self, f: &SheetFlange, e: &Seg2, z: f64) -> EdgeSpec {
|
||||
let n = self.zone_pieces(f, e);
|
||||
let mut ctrl = Vec::with_capacity(BEND_CHAIN_DEGREE * n + 1);
|
||||
for k in 0..n {
|
||||
let c = self.zone_piece(f, e, z, k as f64 / n as f64, (k + 1) as f64 / n as f64);
|
||||
ctrl.extend_from_slice(if k == 0 { &c } else { &c[1..] });
|
||||
let breaks = self.zone_breaks(f, e);
|
||||
let mut ctrl = Vec::with_capacity(breaks.len() * 3);
|
||||
for w in breaks.windows(2) {
|
||||
let (t0, t1) = (w[0], w[1]);
|
||||
let h = t1 - t0;
|
||||
let ((p0, d0), (p1, d1)) = (self.zone_edge_at(f, e, z, t0), self.zone_edge_at(f, e, z, t1));
|
||||
if ctrl.is_empty() {
|
||||
ctrl.push(p0);
|
||||
}
|
||||
ctrl.extend([p0 + d0 * (h / 3.0), p1 - d1 * (h / 3.0), p1]);
|
||||
}
|
||||
EdgeSpec::Chain { degree: BEND_CHAIN_DEGREE, ctrl: ctrl.into() }
|
||||
EdgeSpec::Chain { ctrl: ctrl.into() }
|
||||
}
|
||||
|
||||
/// A flat edge of a piece as a 3D edge at height `z`.
|
||||
@@ -4961,34 +4918,21 @@ mod tests {
|
||||
assert!(s.zone_point(&f, q, z).0.dist(s.map3(Piece::Zone(0), q, z)) < 1e-12);
|
||||
}
|
||||
// A flat line across the whole zone, 15 mm along the bend: the bend angle and the
|
||||
// distance along the axis both grow evenly along it. Two pieces of degree 7 follow it
|
||||
// (cubic ones took 32).
|
||||
// distance along the axis both grow evenly along it.
|
||||
let e = Seg2::Line { a: f.p + f.d * 20.0, b: f.p + f.n * s.allowance(&f) + f.d * 35.0 };
|
||||
let n = s.zone_pieces(&f, &e);
|
||||
assert_eq!(n, 2);
|
||||
let breaks = s.zone_breaks(&f, &e);
|
||||
for z in [0.0, 2.0] {
|
||||
let helix = |t: f64| {
|
||||
let (phi, rho) = (angle * t, 3.0 - z);
|
||||
Vec3::new(e.point_at(t).x, setback - rho * phi.sin(), 3.0 - rho * phi.cos())
|
||||
};
|
||||
let EdgeSpec::Chain { degree: 7, ctrl } = s.zone_chain(&f, &e, z) else { panic!("a slanted edge folds to a chain of degree 7") };
|
||||
assert_eq!(ctrl.len(), 7 * n + 1);
|
||||
for k in 0..n {
|
||||
for i in 0..=40 {
|
||||
let x = i as f64 / 40.0;
|
||||
let off = bezier_at(&ctrl[7 * k..=7 * k + 7], x).dist(helix((k as f64 + x) / n as f64));
|
||||
assert!(off < BEND_CHAIN_TOL, "height {z}, piece {k}, {x}: {off}");
|
||||
}
|
||||
}
|
||||
// The pieces are equal, so the chain is one smooth curve: on either side of a joint
|
||||
// the first three differences of the control points are the same.
|
||||
let diff = |p: &[Vec3]| p.windows(2).map(|w| w[1] - w[0]).collect::<Vec<_>>();
|
||||
for k in 1..n {
|
||||
let (mut before, mut after) = (ctrl[7 * k - 3..=7 * k].to_vec(), ctrl[7 * k..=7 * k + 3].to_vec());
|
||||
for order in 1..=3 {
|
||||
(before, after) = (diff(&before), diff(&after));
|
||||
let (b, a) = (before[before.len() - 1], after[0]);
|
||||
assert!(b.dist(a) < 1e-12, "height {z}, joint {k}, order {order}: {b:?} vs {a:?}");
|
||||
let EdgeSpec::Chain { ctrl } = s.zone_chain(&f, &e, z) else { panic!("a slanted edge folds to a chain") };
|
||||
assert_eq!(ctrl.len(), 3 * (breaks.len() - 1) + 1);
|
||||
for (k, w) in breaks.windows(2).enumerate() {
|
||||
for x in [0.0, 0.1, 0.37, 0.5, 0.81, 1.0] {
|
||||
let p = cubic_at(ctrl[3 * k], ctrl[3 * k + 1], ctrl[3 * k + 2], ctrl[3 * k + 3], x);
|
||||
let exact = helix(w[0] + (w[1] - w[0]) * x);
|
||||
assert!(p.dist(exact) < BEND_CHAIN_TOL, "height {z}, piece {k}: {}", p.dist(exact));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5653,7 +5597,7 @@ mod tests {
|
||||
assert!((s.base.area() - base).abs() < tol, "{what}: {} vs {base}", s.base.area());
|
||||
assert!((flat_area(&s) - (base + len * (ba + panel))).abs() < 1e-6, "{what}: {}", flat_area(&s));
|
||||
// (A sliver 0.0001 wide is below the flat pattern's shortest edge.)
|
||||
if !(0.0..=1e-3).contains(&hair) {
|
||||
if hair < 0.0 || hair > 1e-3 {
|
||||
holds_the_flat_material(&s, &what);
|
||||
} else {
|
||||
let b = s.solid().unwrap_or_else(|e| panic!("{what}: no solid: {e}"));
|
||||
@@ -7492,59 +7436,6 @@ mod tests {
|
||||
assert!(s.solid().is_ok() && s.flat_regions().unwrap().len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_bend_end_folds_to_two_smooth_pieces_on_its_helix() {
|
||||
// The tray of `a_tear_cuts_each_bend_from_the_corner_to_its_flanges_end` (T = 2, R = 1):
|
||||
// each of its eight torn bend ends is the wall ruled between a helix on the bend's inner
|
||||
// face and one on its outer face, `bend_end` at the turn φ from 0 to θ. Cubic pieces took
|
||||
// 32 at either angle, which a viewer draws as 32 strips; two pieces of degree 7 hold the
|
||||
// helix to within the chains' tolerance.
|
||||
for deg in [90.0f64, 72.0] {
|
||||
let what = format!("{deg}°");
|
||||
let (s, _) = tray(&torn(), deg, 38.6);
|
||||
let mut work = FlatWork::new();
|
||||
let cells = s.cells_with_work(&mut work).unwrap();
|
||||
let faces = s.faces(&cells, 0.0, s.t, &mut work).unwrap();
|
||||
let walls: Vec<(&EdgeSpec, &EdgeSpec)> = faces
|
||||
.iter()
|
||||
.filter_map(|f| match &f.surface {
|
||||
SurfSpec::Ruled { a, b } => Some((a, b)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(walls.len(), 8, "{what}");
|
||||
let th = deg.to_radians();
|
||||
for (bottom, top) in walls {
|
||||
for (chain, z) in [(bottom, 0.0), (top, s.t)] {
|
||||
let EdgeSpec::Chain { ctrl, .. } = chain else { panic!("{what}: a torn end folds to a chain") };
|
||||
assert_eq!(ctrl.len(), 15, "{what}: two pieces of degree 7");
|
||||
// The torn end this chain runs along, and which way.
|
||||
let (first, last) = (ctrl[0], ctrl[ctrl.len() - 1]);
|
||||
let end = s.flanges.iter().flat_map(|f| [(f, false), (f, true)]).find_map(|(f, at_end)| {
|
||||
let at = |phi: f64| s.bend_end(f, at_end, phi, z);
|
||||
if at(0.0).dist(first) < 1e-9 && at(th).dist(last) < 1e-9 {
|
||||
Some((f, at_end, false))
|
||||
} else if at(th).dist(first) < 1e-9 && at(0.0).dist(last) < 1e-9 {
|
||||
Some((f, at_end, true))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let Some((f, at_end, back)) = end else { panic!("{what}: {first:?} to {last:?} is no torn end") };
|
||||
for k in 0..2 {
|
||||
for i in 0..=40 {
|
||||
let t = (k as f64 + i as f64 / 40.0) / 2.0;
|
||||
let exact = s.bend_end(f, at_end, th * if back { 1.0 - t } else { t }, z);
|
||||
let off = bezier_at(&ctrl[7 * k..=7 * k + 7], i as f64 / 40.0).dist(exact);
|
||||
assert!(off < BEND_CHAIN_TOL, "{what}: height {z}, {t}: {off}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
holds_the_flat_material(&s, &what);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_bend_end_is_no_flat_face() {
|
||||
use std::f64::consts::{FRAC_PI_2, SQRT_2};
|
||||
|
||||
@@ -113,7 +113,6 @@ fn box_fillet_cut_timeline() {
|
||||
body: None,
|
||||
style: Default::default(),
|
||||
fit: Default::default(),
|
||||
corner: Default::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -184,7 +183,6 @@ fn errors_are_reported_not_fatal() {
|
||||
body: None,
|
||||
style: Default::default(),
|
||||
fit: Default::default(),
|
||||
corner: Default::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -50,7 +50,6 @@ impl Walk for crate::document::Operation {}
|
||||
impl Walk for solidcraft_kernel::Continuity {}
|
||||
impl Walk for crate::document::Direction {}
|
||||
impl Walk for crate::document::FilletFit {}
|
||||
impl Walk for crate::document::FilletCorner {}
|
||||
impl Walk for crate::document::MeshData {}
|
||||
impl Walk for crate::document::RevolveConvention {}
|
||||
impl Walk for crate::document::CoilSection {}
|
||||
|
||||
@@ -214,18 +214,10 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = component(s, p, "component", cmd)?;
|
||||
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"))?;
|
||||
let d = s.doc_mut();
|
||||
if id == 0 {
|
||||
d.name = name.to_string();
|
||||
} else if let Some(c) = d.components.iter_mut().find(|c| c.id == id) {
|
||||
let old = std::mem::replace(&mut c.name, name.to_string());
|
||||
// Placements still named after the component ("Old:2") follow it (#1665); others keep theirs.
|
||||
for o in d.occurrences.iter_mut().filter(|o| o.component == id) {
|
||||
let k = o.name.strip_prefix(old.as_str()).and_then(|r| r.strip_prefix(':'));
|
||||
if let Some(k) = k.filter(|k| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())) {
|
||||
o.name = format!("{name}:{k}");
|
||||
}
|
||||
}
|
||||
s.doc_mut().name = name.to_string();
|
||||
} else if let Some(c) = s.doc_mut().components.iter_mut().find(|c| c.id == id) {
|
||||
c.name = name.to_string();
|
||||
}
|
||||
Ok(json!({"component": id, "name": name}))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use solidcraft_doc::Document;
|
||||
use solidcraft_doc::joints::cam::CamProfile;
|
||||
use solidcraft_doc::joints::{Assembly, Coupling, JointOrigin, Size, Snap};
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
@@ -103,31 +102,9 @@ fn budget(assembly: &Assembly) -> Result<()> {
|
||||
return Err(invalid("exploded view contains non-finite moves"));
|
||||
}
|
||||
}
|
||||
if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite() && l.lift.iter().all(|v| v.is_finite())) {
|
||||
if !assembly.links.iter().all(|l| l.ratio.is_finite() && l.offset.is_finite()) {
|
||||
return Err(invalid("motion link contains non-finite values"));
|
||||
}
|
||||
for cam in assembly.links.iter().filter_map(|l| match &l.coupling {
|
||||
Some(Coupling::Cam(c)) => Some(c),
|
||||
_ => None,
|
||||
}) {
|
||||
add_references(&mut references, cam.tip.iter().count())?;
|
||||
if let Some(tip) = &cam.tip {
|
||||
finite_origin(tip)?;
|
||||
}
|
||||
match &cam.profile {
|
||||
CamProfile::Sketch { curves, .. } => {
|
||||
add_references(&mut references, curves.len())?;
|
||||
curves.iter().try_for_each(|c| text(c))?;
|
||||
}
|
||||
CamProfile::Edges { picks, names, .. } => {
|
||||
add_references(&mut references, picks.len() + names.len())?;
|
||||
if !picks.iter().all(|p| p.is_finite()) {
|
||||
return Err(invalid("motion link contains non-finite values"));
|
||||
}
|
||||
names.iter().try_for_each(|n| text(n))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for size in assembly.links.iter().filter_map(|l| l.coupling.as_ref()).flat_map(Coupling::sizes) {
|
||||
match size {
|
||||
Size::Length(v) if !v.is_finite() => return Err(invalid("motion link contains non-finite values")),
|
||||
@@ -323,26 +300,12 @@ pub(super) fn clone_assembly(
|
||||
continue;
|
||||
}
|
||||
let mut item = old.clone();
|
||||
// A gear's picked round faces are on occurrences of the copy too, and so are a cam's
|
||||
// profile and its follower's tip.
|
||||
// A gear's picked round faces are on occurrences of the copy too.
|
||||
let faces = item.coupling.as_mut().is_none_or(|c| {
|
||||
let sizes = c.sizes_mut().into_iter().all(|size| match size {
|
||||
c.sizes_mut().into_iter().all(|size| match size {
|
||||
Size::Circle(o) => origin(o, occurrences, features, bodies).map(|new| *o = new).is_some(),
|
||||
_ => true,
|
||||
});
|
||||
let Coupling::Cam(cam) = c else { return sizes };
|
||||
let tip = match &mut cam.tip {
|
||||
Some(t) => origin(t, occurrences, features, bodies).map(|new| *t = new).is_some(),
|
||||
None => true,
|
||||
};
|
||||
let profile = match &mut cam.profile {
|
||||
CamProfile::Sketch { sketch, .. } => features.get(sketch).map(|new| *sketch = *new).is_some(),
|
||||
CamProfile::Edges { occurrence, names, .. } => {
|
||||
occurrences.get(occurrence).map(|new| *occurrence = *new).is_some()
|
||||
&& names.iter_mut().all(|n| n.is_empty() || face_name(n, features, bodies).map(|new| *n = new).is_some())
|
||||
}
|
||||
};
|
||||
sizes && tip && profile
|
||||
})
|
||||
});
|
||||
match (joints.get(&old.a), joints.get(&old.b)) {
|
||||
(Some(aa), Some(bb)) if faces => {
|
||||
|
||||
@@ -44,8 +44,8 @@ fn documents() -> (Document, Document) {
|
||||
NamedOrigin { name: "Outside".into(), origin: at(9) },
|
||||
];
|
||||
source.assembly.links = vec![
|
||||
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None, lift: Vec::new() },
|
||||
MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() },
|
||||
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.3, coupling: None },
|
||||
MotionLink { a: 1, ia: 0, b: 3, ib: 0, ratio: 1.0, offset: 0.0, coupling: None },
|
||||
];
|
||||
source.assembly.contact_sets = vec![
|
||||
ContactSet { id: 1, name: "Internal contact".into(), occurrences: vec![1, 2], suppressed: true },
|
||||
@@ -106,8 +106,8 @@ fn copied_gears_take_their_picked_faces_along() {
|
||||
let circle = |face: &str| Size::Circle(JointOrigin { occurrence: 1, snap: Snap::CircleCenter { pick: Vec3::X, face: Some(face.into()) } });
|
||||
let gear = |ra| Coupling::Gear { ra, rb: Size::Length(5.0), internal: false, reverse: false };
|
||||
source.assembly.links = vec![
|
||||
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))), lift: Vec::new() },
|
||||
MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))), lift: Vec::new() },
|
||||
MotionLink { a: 1, ia: 0, b: 2, ib: 0, ratio: -2.0, offset: 0.0, coupling: Some(gear(circle("F1:side"))) },
|
||||
MotionLink { a: 2, ia: 0, b: 1, ib: 0, ratio: -0.5, offset: 0.0, coupling: Some(gear(circle("F99:side"))) },
|
||||
];
|
||||
let mut destination = source.clone();
|
||||
destination.occurrences.extend([101, 102].map(occurrence));
|
||||
|
||||
@@ -27,13 +27,9 @@ struct CachedBody {
|
||||
size: f64,
|
||||
}
|
||||
|
||||
/// A member of a contact set: (occurrence id, name).
|
||||
pub(super) type Member = (u64, String);
|
||||
|
||||
pub(super) struct ContactGeometry {
|
||||
bodies: Vec<CachedBody>,
|
||||
/// Body indices, and the set members (occurrence id, name) they are under.
|
||||
pairs: Vec<(usize, usize, Member, Member)>,
|
||||
pairs: Vec<(usize, usize, String, String)>,
|
||||
step: f64,
|
||||
}
|
||||
|
||||
@@ -45,12 +41,6 @@ impl ContactGeometry {
|
||||
} else {
|
||||
assembly.contact_sets.iter().filter(|set| !set.suppressed).map(|set| set.occurrences.clone()).collect()
|
||||
};
|
||||
Self::of_sets(s, &sets)
|
||||
}
|
||||
|
||||
/// The geometry of the bodies under `sets` (occurrence ids), paired as contact sets pair
|
||||
/// them: bodies under different members of one set.
|
||||
pub(super) fn of_sets(s: &Session, sets: &[Vec<u64>]) -> Result<Self> {
|
||||
let mut out = Self { bodies: Vec::new(), pairs: Vec::new(), step: f64::INFINITY };
|
||||
if sets.is_empty() {
|
||||
return Ok(out);
|
||||
@@ -130,7 +120,7 @@ impl ContactGeometry {
|
||||
}
|
||||
}
|
||||
let mut pairs = BTreeSet::new();
|
||||
for set in sets {
|
||||
for set in &sets {
|
||||
let tagged: Vec<(usize, u64)> =
|
||||
out.bodies.iter().enumerate().filter_map(|(i, b)| b.path.iter().rev().find(|id| set.contains(id)).map(|id| (i, *id))).collect();
|
||||
for (i, (a, oa)) in tagged.iter().enumerate() {
|
||||
@@ -142,7 +132,7 @@ impl ContactGeometry {
|
||||
}
|
||||
}
|
||||
let name = |id| s.doc.occurrences.iter().find(|o| o.id == id).map(|o| o.name.clone()).unwrap_or_default();
|
||||
out.pairs = pairs.into_iter().map(|(a, b, oa, ob)| (a, b, (oa, name(oa)), (ob, name(ob)))).collect();
|
||||
out.pairs = pairs.into_iter().map(|(a, b, oa, ob)| (a, b, name(oa), name(ob))).collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -150,21 +140,6 @@ impl ContactGeometry {
|
||||
!self.pairs.is_empty()
|
||||
}
|
||||
|
||||
/// Keeps only the pairs of set members (occurrence ids) `keep` takes.
|
||||
pub(super) fn keep_pairs(&mut self, keep: impl Fn(u64, u64) -> bool) {
|
||||
self.pairs.retain(|(_, _, a, b)| keep(a.0, b.0));
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// How many pairs of set members are checked against each other.
|
||||
pub(super) fn pair_count(&self) -> usize {
|
||||
self.pairs.iter().map(|(_, _, a, b)| (a.0.min(b.0), a.0.max(b.0))).collect::<BTreeSet<_>>().len()
|
||||
}
|
||||
|
||||
fn frame(body: &CachedBody, s: &Session) -> Result<Mat> {
|
||||
let mut frame = IDENTITY;
|
||||
for id in &body.path {
|
||||
@@ -230,16 +205,6 @@ impl ContactGeometry {
|
||||
}
|
||||
|
||||
pub(super) fn first_hit(&self, s: &Session, work: &mut usize) -> Result<Option<(String, String, f64)>> {
|
||||
Ok(self.hits(s, work, MAX_WORK, false)?.into_iter().next().map(|(a, b, depth)| (a.1, b.1, depth)))
|
||||
}
|
||||
|
||||
/// The pairs of set members whose bodies pass through each other in `s`, with how deep the
|
||||
/// first two bodies found go (every pair, or the first found when `all` is false). `work`
|
||||
/// adds up the cost, refused past `budget`.
|
||||
pub(super) fn hits(&self, s: &Session, work: &mut usize, budget: usize, all: bool) -> Result<Vec<(Member, Member, f64)>> {
|
||||
let mut out: Vec<(Member, Member, f64)> = Vec::new();
|
||||
// The member pairs found so far (lower id first).
|
||||
let mut found: BTreeSet<(u64, u64)> = BTreeSet::new();
|
||||
let meshes: Vec<Mesh> = self
|
||||
.bodies
|
||||
.iter()
|
||||
@@ -249,19 +214,11 @@ impl ContactGeometry {
|
||||
Ok(Mesh { positions, triangles: body.mesh.triangles.clone(), ..Mesh::default() })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
// Each mesh's box once, not once per pair it is in.
|
||||
let boxes: Vec<Aabb3> = meshes.iter().map(Mesh::bounds).collect();
|
||||
for (a, b, oa, ob) in &self.pairs {
|
||||
// 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;
|
||||
}
|
||||
for (a, b, aname, bname) in &self.pairs {
|
||||
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"));
|
||||
};
|
||||
let (aabb, bbb) = (ma.bounds(), mb.bounds());
|
||||
if aabb.max.x < bbb.min.x
|
||||
|| bbb.max.x < aabb.min.x
|
||||
|| aabb.max.y < bbb.min.y
|
||||
@@ -278,18 +235,14 @@ impl ContactGeometry {
|
||||
.saturating_mul(mb.triangles.len())
|
||||
.saturating_add(mb.positions.len().saturating_add(mb.triangles.len().saturating_mul(4)).saturating_mul(ma.triangles.len()));
|
||||
*work = work.saturating_add(cost);
|
||||
if *work > budget {
|
||||
if *work > MAX_WORK {
|
||||
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)) {
|
||||
found.insert((oa.0.min(ob.0), oa.0.max(ob.0)));
|
||||
out.push((oa.clone(), ob.clone(), depth));
|
||||
if !all {
|
||||
break;
|
||||
}
|
||||
return Ok(Some((aname.clone(), bname.clone(), depth)));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.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 perpendicular planar end face at each end; 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)"),
|
||||
.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 perpendicular planar end face at each end; 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); 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?)"),
|
||||
CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect)
|
||||
@@ -55,7 +55,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); 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); diameter | thread (a tapped hole: the tap drill, major − pitch) | 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); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"),
|
||||
.params("position: [x,y,z] on a face | 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); 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); diameter | thread (a tapped hole: the tap drill, major − pitch) | 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); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?; cs_diameter?, cs_angle?; thread?: \"M6\" (cosmetic)"),
|
||||
CommandSpec::new("solid.pipe", "Pipe", pipe)
|
||||
.at("SOLID", "CREATE")
|
||||
.icon("pipe")
|
||||
@@ -79,7 +79,7 @@ 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); modeled?: bool (default false). Cosmetic: the model is unchanged, model.threads lists it. Modeled: cuts the thread profile into the body"),
|
||||
.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). Cosmetic: the model is unchanged, model.threads lists it"),
|
||||
CommandSpec::new("solid.shell", "Shell", shell)
|
||||
.at("SOLID", "MODIFY")
|
||||
.icon("shell")
|
||||
@@ -141,20 +141,6 @@ fn extrude_base(s: &Session, p: &Value) -> Option<(Vec3, Vec3)> {
|
||||
Some((ss.plane.to_world(q), ss.plane.normal()))
|
||||
}
|
||||
|
||||
/// How far an extrude with these parameters goes from its profile along the profile's normal
|
||||
/// (negative: the other way). To an object, the target's height, on whichever side it is: the
|
||||
/// extrude goes there and its `direction` does not count (#1633). Otherwise its distance, turned
|
||||
/// round for the negative direction.
|
||||
pub fn extrude_reach(s: &Session, p: &Value) -> Option<f64> {
|
||||
if let Some(t) = p.get("to").and_then(vec3) {
|
||||
let (base, n) = extrude_base(s, p)?;
|
||||
return Some((t - base).dot(n)).filter(|h| h.is_finite());
|
||||
}
|
||||
let d = s.doc.eval(&expr(p, "distance")?, Kind::Length).ok()?;
|
||||
let dir = str_(p, "direction").map(str::to_ascii_lowercase);
|
||||
Some(if matches!(dir.as_deref(), Some("negative" | "reverse" | "flip")) { -d } else { d })
|
||||
}
|
||||
|
||||
/// How far past the profile [`auto_operation`] looks for material it starts in.
|
||||
const START_PROBE_MM: f64 = 0.1;
|
||||
|
||||
@@ -166,8 +152,10 @@ const START_PROBE_MM: f64 = 0.1;
|
||||
/// 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> {
|
||||
let d = extrude_reach(s, p)?;
|
||||
let symmetric = p.get("to").is_none() && str_(p, "direction").is_some_and(|d| d.eq_ignore_ascii_case("symmetric"));
|
||||
let d = s.doc.eval(&expr(p, "distance")?, Kind::Length).ok()?;
|
||||
let dir = str_(p, "direction").map(str::to_ascii_lowercase);
|
||||
let symmetric = dir.as_deref() == Some("symmetric");
|
||||
let d = if matches!(dir.as_deref(), Some("negative" | "reverse" | "flip")) { -d } else { d };
|
||||
let (base, n) = extrude_base(s, p)?;
|
||||
let st = s.model.state();
|
||||
if st.bodies.is_empty() || !d.is_finite() {
|
||||
@@ -1063,26 +1051,10 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !fit.is_exact() && !style.is_constant() {
|
||||
return Err(bad(cmd, "`fit: reduce` and `fit: taper` take a constant radius"));
|
||||
}
|
||||
// What fills the corners where three blended edges meet.
|
||||
let corner = match str_(p, "corner").map(str::to_ascii_lowercase).as_deref() {
|
||||
None | Some("rolling") => solidcraft_doc::FilletCorner::Rolling,
|
||||
Some("g2") => solidcraft_doc::FilletCorner::G2,
|
||||
Some(o) => return Err(bad(cmd, format!("unknown corner `{o}` (rolling or g2)"))),
|
||||
};
|
||||
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"));
|
||||
}
|
||||
let mut out = add_feature(
|
||||
s,
|
||||
p,
|
||||
FeatureKind::Fillet {
|
||||
edges: edges.into_iter().map(Position).collect(),
|
||||
radius,
|
||||
body: str_(p, "body").map(BodyName::from),
|
||||
style,
|
||||
fit,
|
||||
corner,
|
||||
},
|
||||
FeatureKind::Fillet { edges: edges.into_iter().map(Position).collect(), radius, body: str_(p, "body").map(BodyName::from), style, fit },
|
||||
)?;
|
||||
// The radii the fillet used, when `fit: reduce` reduced it.
|
||||
if let Some(id) = out.get("feature").and_then(Value::as_u64)
|
||||
@@ -1633,36 +1605,10 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(cmd, format!("unknown thread `{t}` (ISO metric, like M6 or M6x0.75)")));
|
||||
}
|
||||
// A position given as length expressions (#1678), say `["leg_h*0.4", "width/2", "t"]`: kept,
|
||||
// so the hole follows the parameters; drilled where they evaluate now.
|
||||
let at: Option<solidcraft_doc::PointExpr> = match p.get("position").and_then(Value::as_array) {
|
||||
Some(a) if points.is_none() && a.len() == 3 && a.iter().any(Value::is_string) => {
|
||||
let mut coords = Vec::with_capacity(3);
|
||||
for v in a {
|
||||
let e = match v {
|
||||
Value::String(x) => x.trim().to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
_ => return Err(bad(cmd, "`position` must be [x, y, z]: numbers or length expressions")),
|
||||
};
|
||||
check_expr(s, &e, Kind::Length, cmd, "position")?;
|
||||
coords.push(solidcraft_doc::Expr::new(e));
|
||||
}
|
||||
let [x, y, z]: [solidcraft_doc::Expr; 3] = coords.try_into().map_err(|_| bad(cmd, "`position` must be [x, y, z]"))?;
|
||||
Some([x, y, z])
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let at_value = match &at {
|
||||
Some([x, y, z]) => {
|
||||
let c = |e: &solidcraft_doc::Expr| s.doc.eval(e, Kind::Length).map_err(|e| bad(cmd, format!("`position`: {e}")));
|
||||
Some(Vec3::new(c(x)?, c(y)?, c(z)?)).filter(|v| v.is_finite())
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let position = match (&points, at_value.or_else(|| p.get("position").and_then(vec3))) {
|
||||
let position = match (&points, p.get("position").and_then(vec3)) {
|
||||
(Some((_, first, _)), None) => *first,
|
||||
(_, Some(x)) => x,
|
||||
(None, None) => return Err(bad(cmd, "`position` must be [x, y, z], numbers or length expressions (or give `sketch` and `points`)")),
|
||||
(None, None) => return Err(bad(cmd, "`position` must be [x, y, z] (or give `sketch` and `points`)")),
|
||||
};
|
||||
let direction = match (p.get("direction").and_then(vec3), &points) {
|
||||
(None, Some((_, _, d))) => *d,
|
||||
@@ -1732,7 +1678,6 @@ fn hole(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&p,
|
||||
FeatureKind::Hole {
|
||||
position: FacePick(position),
|
||||
at,
|
||||
direction: Dir(direction),
|
||||
diameter,
|
||||
depth,
|
||||
@@ -2097,55 +2042,6 @@ mod thin_extrude_tests;
|
||||
#[cfg(test)]
|
||||
#[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.
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod corner_tests {
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: &Value) -> Value {
|
||||
s.execute(id, p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
/// A 20 mm box with its three edges at one corner, filleted by 4 with `corner`.
|
||||
fn cornered(corner: Option<&str>) -> (Session, Value) {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", &json!({"length": 20, "width": 20, "height": 20, "body_name": "B"}));
|
||||
let mut p = json!({"edges": [[10, 0, 0], [0, 10, 0], [0, 0, 10]], "radius": 4});
|
||||
if let Some(c) = corner {
|
||||
p["corner"] = json!(c);
|
||||
}
|
||||
let reply = run(&mut s, "solid.fillet", &p);
|
||||
(s, reply)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_corner_is_the_rolling_ball_and_g2_refuses_clearly() {
|
||||
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();
|
||||
// `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.
|
||||
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());
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[path = "fillet_connected_rounds_tests.rs"]
|
||||
mod fillet_connected_rounds_tests;
|
||||
@@ -161,8 +161,6 @@ fn emboss(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = solidcraft_doc::apply_point(&s.active_component_frame(), local);
|
||||
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;
|
||||
for body in &state.bodies {
|
||||
let definition = body.definition_name();
|
||||
if !targets.is_empty() && !targets.iter().any(|n| n == definition || n == &body.name) {
|
||||
@@ -181,30 +179,14 @@ fn emboss(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
inside.then_some(((at - a).dot(n).abs(), *face as usize))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0));
|
||||
match closest {
|
||||
Some((distance, index)) if distance < (body.body.size() * 1e-3).max(1e-3) => candidates.push((body, index)),
|
||||
Some((distance, _)) if nearest.is_none_or(|(d, _)| distance < d) => nearest = Some((distance, body.name.as_str())),
|
||||
_ => {}
|
||||
if let Some((distance, index)) = closest
|
||||
&& distance < (body.body.size() * 1e-3).max(1e-3)
|
||||
{
|
||||
candidates.push((body, index));
|
||||
}
|
||||
}
|
||||
// #392: say what is wrong with the point, not only that it picks no single face.
|
||||
let point = format!("[{}, {}, {}]", local.x, local.y, local.z);
|
||||
match (candidates.as_slice(), nearest) {
|
||||
([], Some((d, body))) => {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("`face` {point} lies on no face: the nearest, on `{body}`, is {d:.3} mm away; give a point on the face"),
|
||||
));
|
||||
}
|
||||
([], None) => return Err(bad(cmd, format!("`face` {point} lies on no face of the target bodies"))),
|
||||
([_], _) => {}
|
||||
(more, _) => {
|
||||
let names: Vec<&str> = more.iter().map(|(b, _)| b.name.as_str()).collect();
|
||||
return Err(bad(
|
||||
cmd,
|
||||
format!("`face` {point} lies on faces of {} bodies ({}): name one in `targets`", names.len(), names.join(", ")),
|
||||
));
|
||||
}
|
||||
if candidates.len() != 1 {
|
||||
return Err(bad(cmd, "`face` must identify exactly one target body surface"));
|
||||
}
|
||||
let (selected, index) = candidates.first().copied().ok_or_else(|| bad(cmd, "no target face"))?;
|
||||
let name = selected.definition_name();
|
||||
|
||||
@@ -92,23 +92,6 @@ fn emboss_and_deboss_on_a_face() {
|
||||
assert!(s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "mode": "sideways"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emboss_face_off_the_part_says_how_far() {
|
||||
// #392: a point beside the face was refused with "`face` must identify exactly one target
|
||||
// body surface", which didn't say the point was off the face.
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "A"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 10]}, "name": "Logo"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [15, 15]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 11.25]})).unwrap_err().to_string();
|
||||
assert!(e.contains("[20, 15, 11.25] lies on no face: the nearest, on `A`, is 1.250 mm away"), "{e}");
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 30, "height": 10, "corner": [40, 0, 0], "operation": "new_body", "body_name": "B"}));
|
||||
let e = s.execute("solid.emboss", &json!({"sketch": "Logo", "depth": 1, "face": [40, 15, 5]})).unwrap_err().to_string();
|
||||
assert!(e.contains("lies on faces of 2 bodies (A, B): name one in `targets`"), "{e}");
|
||||
run(&mut s, "solid.emboss", json!({"sketch": "Logo", "depth": 1, "face": [20, 15, 10]}));
|
||||
}
|
||||
|
||||
fn cylinder_badge() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name":"badge_depth","expression":"1 mm"}));
|
||||
@@ -782,60 +765,6 @@ fn a_tapered_text_joins_a_block_on_its_face_or_hanging_over_its_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A tapered foot extruded 3 mm down from a part's bottom face and joined (#1534). Run on into
|
||||
/// the part with their slope, sides that narrow the foot away from the face widened it past the
|
||||
/// face: a box got a lip round its walls (0.16 mm wide, and nothing said), a cylinder's join found
|
||||
/// no result, and sides that widen the foot met the face's edge there. A foot on the whole face is
|
||||
/// sewn on along it; one drawn just inside the face's edge starts on it. Either way: the part plus
|
||||
/// the frustum, and nothing beside the part's walls.
|
||||
#[test]
|
||||
fn a_tapered_foot_under_a_part_joins_as_drawn() {
|
||||
// (round, the foot's half width: the whole face, or just inside its edge)
|
||||
for (round, half) in [(false, 15.0), (true, 15.0), (false, 14.9)] {
|
||||
for taper in [-20.0f64, 20.0] {
|
||||
let t = taper.to_radians().tan();
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane":"XY"}));
|
||||
if round {
|
||||
run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":15}));
|
||||
} else {
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-15,-15],"p1":[15,15]}));
|
||||
}
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance":10,"body_name":"B"}));
|
||||
let taper_deg = format!("{taper} deg");
|
||||
if half < 15.0 {
|
||||
run(&mut s, "sketch.create", json!({"plane":"XY"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0":[-half,-half],"p1":[half,half]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance":3,"direction":"negative","operation":"join","taper":taper_deg}));
|
||||
} else {
|
||||
let foot = json!({"face":[5,1,0],"face_body":"B","distance":3,"direction":"positive","operation":"join","taper":taper_deg});
|
||||
run(&mut s, "solid.extrude", foot);
|
||||
}
|
||||
let (part, frustum) = if round {
|
||||
let r = 15.0 + 3.0 * t;
|
||||
(std::f64::consts::PI * 225.0 * 10.0, std::f64::consts::PI * (225.0 + 15.0 * r + r * r))
|
||||
} else {
|
||||
let side = 2.0 * half + 6.0 * t;
|
||||
(9000.0, 4.0 * half * half + 2.0 * half * side + side * side)
|
||||
};
|
||||
let v = volume(&mut s);
|
||||
// The cylinder is measured on its mesh; a foot that starts on the face stands straight
|
||||
// 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);
|
||||
let state = s.model.state();
|
||||
let mesh = state.body("B").unwrap().mesh();
|
||||
// Beside the part, above the foot's start: nothing.
|
||||
let out = |x: f64, y: f64| if round { x.hypot(y) } else { x.abs().max(y.abs()) } > 15.0 + 1e-6;
|
||||
let beside = mesh.positions.iter().filter(|p| p.z > 1e-6 && out(p.x, p.y)).count();
|
||||
assert_eq!(beside, 0, "round {round}, half {half}, taper {taper}: {:?}", mesh.bounds());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A rounded part as drawn in the app: a rectangle and a quarter circle tangent to its top
|
||||
/// line, extruded together. The arc (about (62.17, -21), radius 21) ends square at the front
|
||||
/// face and in a knife-edge tip where it runs into the back face.
|
||||
@@ -1222,32 +1151,3 @@ fn a_line_of_text_cut_through_or_joined_in_relief_is_one_boolean() {
|
||||
assert_eq!(pieces, 1);
|
||||
assert!(rel(relief - before, 2.0 * (before - one)) < 2e-3, "{} vs {}", relief - before, 2.0 * (before - one));
|
||||
}
|
||||
|
||||
/// The same line of text cut again, deeper: the new walls lie on the letters' walls. The 2D route
|
||||
/// takes it as one exact boolean: a point a hair from a segment's end is that end, a sliver of a
|
||||
/// letter's curve shorter than the tolerance is dropped, and a piece of a letter so short that the
|
||||
/// engraved walls read it as an arc while the tool has the curve itself is one edge. Before, the
|
||||
/// sewing found a degenerate edge, then the faces did not close, and the cut went to the B-rep
|
||||
/// boolean's retries (90 s).
|
||||
#[test]
|
||||
fn a_line_of_text_cut_again_deeper_is_one_exact_boolean() {
|
||||
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":[105,26]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance":40}));
|
||||
let cut = |s: &mut Session, depth: f64| {
|
||||
let before = volume(s);
|
||||
run(s, "sketch.create", json!({"plane":"XY","offset":40}));
|
||||
run(s, "sketch.text", json!({"text":"textvraiment tres long","at":[3,9],"height":6.5}));
|
||||
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:?}");
|
||||
before - volume(s)
|
||||
};
|
||||
let first = cut(&mut s, 1.0);
|
||||
// Cut again 2 mm deep: one more millimetre of the letters.
|
||||
let again = cut(&mut s, 2.0);
|
||||
assert!(rel(again, first) < 1e-3, "{first} {again}");
|
||||
}
|
||||
@@ -278,19 +278,6 @@ fn default_name_for(name: &str, path: &str) -> Option<String> {
|
||||
(!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<String> {
|
||||
if let Some(stem) = default_name_for(name, path) {
|
||||
return Some(stem);
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
/// Rename the design, and the undo and redo states that still carry the old name, so undo
|
||||
/// does not bring the default name back and leave the design looking changed.
|
||||
fn rename_design(s: &mut Session, from: &str, to: &str) {
|
||||
@@ -304,9 +291,8 @@ 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) -> Result<Value> {
|
||||
solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
// 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 design names it after its file (not an undoable edit).
|
||||
let renamed = default_name_for(&s.doc.name, path).map(|stem| (s.doc.name.clone(), stem));
|
||||
if let Some((from, to)) = &renamed {
|
||||
rename_design(s, from, to);
|
||||
}
|
||||
@@ -897,20 +883,9 @@ mod tests {
|
||||
// Undoing the box does not bring the old name back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.name, "bracket");
|
||||
// Saved under another file, a name taken from the old file follows it (#1710), in the
|
||||
// file too, so reopening shows it.
|
||||
let copy = dir.join("copy.solidcraft");
|
||||
s.execute("file.save_as", &json!({"path":copy})).unwrap();
|
||||
assert_eq!(s.doc.name, "copy");
|
||||
let mut reopened = Session::default();
|
||||
reopened.execute("doc.open", &json!({"path":copy})).unwrap();
|
||||
assert_eq!(reopened.doc.name, "copy");
|
||||
// Saving again to the same file changes nothing.
|
||||
s.execute("file.save", &json!({})).unwrap();
|
||||
assert_eq!(s.doc.name, "copy");
|
||||
// As in the issue: a design opened from its file, then saved as another.
|
||||
reopened.execute("file.save_as", &json!({"path":dir.join("third.solidcraft")})).unwrap();
|
||||
assert_eq!(reopened.doc.name, "third");
|
||||
// Saving under another file keeps the name it now has.
|
||||
s.execute("file.save_as", &json!({"path":dir.join("copy.solidcraft")})).unwrap();
|
||||
assert_eq!(s.doc.name, "bracket");
|
||||
// A failed save leaves the name alone.
|
||||
let mut failed = Session::default();
|
||||
assert!(failed.execute("file.save_as", &json!({"path":dir.join("missing-dir").join("plate.solidcraft")})).is_err());
|
||||
|
||||
+16
-169
@@ -7,7 +7,6 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::expr::Kind;
|
||||
use solidcraft_doc::joints::cam::{self, Cam, CamProfile, Follower};
|
||||
use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, JointOrigin, MotionLink, NamedOrigin, Size, Snap};
|
||||
use solidcraft_geom::{Aabb3, Vec3};
|
||||
|
||||
@@ -61,9 +60,6 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
travel per turn (mm or an expression); reverse?: bool (a left-hand thread); link?: index (replace that motion link) → link, \
|
||||
ratio (mm per degree, or degrees per mm); b keeps where it is",
|
||||
),
|
||||
CommandSpec::new("joint.cam", "Cam", cam_cmd).at("SOLID", "ASSEMBLE").icon("cam").params(
|
||||
"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",
|
||||
),
|
||||
CommandSpec::new("joint.limits", "Joint Limits", limits).params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),
|
||||
CommandSpec::new("joint.edit", "Edit Joint", edit).params("joint; type?, flip?, offset?, angle?, suppressed?, name?"),
|
||||
CommandSpec::new("joint.delete", "Delete Joint", delete).params("joint: id|name (or origin: name, link: index)"),
|
||||
@@ -84,30 +80,29 @@ pub fn resolve(s: &mut Session) -> joints::Solution {
|
||||
resolve_holding(s, &BTreeMap::new())
|
||||
}
|
||||
|
||||
/// Work out the ratios (and cam tables) of the coupled motion links again (a radius, a parameter
|
||||
/// or a cam's profile may have changed). A coupling that can't be worked out (its face gone)
|
||||
/// keeps its last ratio and table; `joint.list` says why.
|
||||
/// Work out the ratios of the coupled motion links again (a radius or a parameter may have
|
||||
/// changed). A coupling that can't be worked out (its face gone) keeps its last ratio;
|
||||
/// `joint.list` says why.
|
||||
fn recouple(s: &mut Session) {
|
||||
if s.doc.assembly.links.iter().all(|l| l.coupling.is_none()) {
|
||||
return;
|
||||
}
|
||||
let st = s.model.state();
|
||||
let changed: Vec<(usize, (f64, Vec<f64>))> = s
|
||||
let changed: Vec<(usize, f64)> = s
|
||||
.doc
|
||||
.assembly
|
||||
.links
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, l)| joints::coupling_values(&s.doc, &st, l)?.ok().filter(|(r, t)| *r != l.ratio || *t != l.lift).map(|v| (i, v)))
|
||||
.filter_map(|(i, l)| joints::coupling_ratio(&s.doc, &st, l)?.ok().filter(|r| *r != l.ratio).map(|r| (i, r)))
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let doc = s.doc_mut();
|
||||
for (i, (r, t)) in changed {
|
||||
for (i, r) in changed {
|
||||
if let Some(l) = doc.assembly.links.get_mut(i) {
|
||||
l.ratio = r;
|
||||
l.lift = t;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -310,29 +305,8 @@ fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<JointOrigin
|
||||
}
|
||||
};
|
||||
let o = JointOrigin { occurrence, snap };
|
||||
match joints::resolve_origin(&s.doc, &s.model.state(), &o) {
|
||||
Ok(_) => Ok(o),
|
||||
// A circle given by its centre, where no face lies (#393).
|
||||
Err(e) => match (what == "circle").then(|| circle_centre(s, occurrence, local(world))).flatten() {
|
||||
Some(snap) => Ok(JointOrigin { occurrence, snap }),
|
||||
None => Err(bad(cmd, e.to_string())),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The round end of a cylindrical face of the occurrence's bodies centred at `pick`: a point on
|
||||
/// its axis there, pointing out of that end (as picking its circular edge gives).
|
||||
fn circle_centre(s: &Session, occurrence: u64, pick: Vec3) -> Option<Snap> {
|
||||
let component = if occurrence == 0 { 0 } else { s.doc.occurrences.iter().find(|o| o.id == occurrence)?.component };
|
||||
let st = s.model.state();
|
||||
let c = st
|
||||
.bodies
|
||||
.iter()
|
||||
.filter(|b| s.doc.model_body_component(b) == component)
|
||||
.find_map(|b| solidcraft_doc::kernel::cylinder_end_at(&b.body, pick))?;
|
||||
let along = (pick - c.axis_point).dot(c.axis);
|
||||
let (at, dir) = if (along - c.start).abs() <= (c.end - along).abs() { (c.start, -1.0) } else { (c.end, 1.0) };
|
||||
Some(Snap::Point { point: c.axis_point + c.axis * at, z: Some(c.axis * dir) })
|
||||
joints::resolve_origin(&s.doc, &s.model.state(), &o).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
pub(crate) fn joint_id(s: &Session, v: Option<&Value>, cmd: &str) -> Result<u64> {
|
||||
@@ -714,7 +688,7 @@ fn motion_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => 0.0,
|
||||
};
|
||||
let ratio = ratio * ratio_scale(s, a, ia, b, ib);
|
||||
s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None, lift: Vec::new() });
|
||||
s.doc_mut().assembly.links.push(MotionLink { a, ia, b, ib, ratio, offset, coupling: None });
|
||||
let sol = resolve(s);
|
||||
Ok(sol_json(&sol, p))
|
||||
}
|
||||
@@ -725,10 +699,7 @@ fn size_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Size> {
|
||||
match p.get(key) {
|
||||
Some(Value::Number(n)) => n.as_f64().map(Size::Length).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite length"))),
|
||||
Some(Value::String(t)) if t.len() <= 1000 => Ok(Size::Expr(t.trim().to_string())),
|
||||
Some(o @ Value::Object(m)) if m.contains_key("circle") => match origin_param(s, Some(o), cmd)? {
|
||||
o @ JointOrigin { snap: Snap::CircleCenter { .. }, .. } => Ok(Size::Circle(o)),
|
||||
_ => Err(bad(cmd, format!("`{key}`: give a point on the round face, not its centre"))),
|
||||
},
|
||||
Some(o @ Value::Object(m)) if m.contains_key("circle") => Ok(Size::Circle(origin_param(s, Some(o), cmd)?)),
|
||||
_ => Err(bad(cmd, format!("`{key}` must be a length (mm or an expression) or a round face ({{circle: [x, y, z]}})"))),
|
||||
}
|
||||
}
|
||||
@@ -771,7 +742,7 @@ fn gear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
internal: bool_(p, "internal").unwrap_or(false),
|
||||
reverse: reverse(p),
|
||||
};
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
|
||||
}
|
||||
|
||||
fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -779,7 +750,7 @@ fn rack_pinion(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (a, b) = joint_pair(s, p, cmd)?;
|
||||
let (ia, ib) = turn_and_travel(s, a, b, cmd)?;
|
||||
let c = Coupling::RackPinion { radius: size_param(s, p, "radius", cmd)?, reverse: reverse(p) };
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
|
||||
}
|
||||
|
||||
fn screw(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -799,120 +770,7 @@ fn screw(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let c = Coupling::Screw { pitch: size_param(s, p, "pitch", cmd)?, reverse: reverse(p) };
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c), lift: Vec::new() })
|
||||
}
|
||||
|
||||
fn cam_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "joint.cam";
|
||||
let (a, b) = joint_pair(s, p, cmd)?;
|
||||
let kind = |id: u64| s.doc.assembly.joints.iter().find(|j| j.id == id).map(|j| j.kind);
|
||||
if kind(a) != Some(JointKind::Revolute) {
|
||||
return Err(bad(cmd, "the cam (a) turns on a revolute joint"));
|
||||
}
|
||||
let oscillating = match kind(b) {
|
||||
Some(JointKind::Slider) => false,
|
||||
Some(JointKind::Revolute) => true,
|
||||
_ => return Err(bad(cmd, "the follower (b) is a slider or a revolute joint")),
|
||||
};
|
||||
let follower = match str_(p, "follower").unwrap_or("knife") {
|
||||
"knife" => Follower::Knife,
|
||||
"roller" => Follower::Roller { radius: size_param(s, p, "radius", cmd)? },
|
||||
"flat" => Follower::Flat,
|
||||
_ => return Err(bad(cmd, "`follower` is knife, roller or flat")),
|
||||
};
|
||||
if oscillating && p.get("tip").is_none() && !matches!(follower, Follower::Roller { radius: Size::Circle(_) }) {
|
||||
return Err(bad(cmd, "an oscillating follower needs `tip`: its knife's point or its roller's centre ({circle: [x, y, z]} on the roller)"));
|
||||
}
|
||||
let tip = match p.get("tip") {
|
||||
Some(v) => Some(origin_param(s, Some(v), cmd)?),
|
||||
None => None,
|
||||
};
|
||||
let mut c = Cam { profile: cam_profile(s, p, cmd)?, follower, tip, reverse: false };
|
||||
let probe = MotionLink { a, ia: 0, b, ib: 0, ratio: 1.0, offset: 0.0, coupling: None, lift: Vec::new() };
|
||||
let st = s.model.state();
|
||||
c.reverse = cam::default_reverse(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))? != bool_(p, "flip").unwrap_or(false);
|
||||
let offset = cam::follower_offset(&s.doc, &st, &probe, &c).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let reverse = c.reverse;
|
||||
let mut out = couple(s, p, cmd, MotionLink { coupling: Some(Coupling::Cam(c)), ..probe })?;
|
||||
let index = out["link"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(usize::MAX);
|
||||
if let (Some(o), Some(l)) = (out.as_object_mut(), s.doc.assembly.links.get(index)) {
|
||||
o.remove("ratio");
|
||||
o.insert("lift".into(), lift_json(l, oscillating));
|
||||
o.insert("reverse".into(), json!(reverse));
|
||||
if !oscillating {
|
||||
o.insert("follower_offset".into(), json!(offset));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A cam's follower travel over a turn of the cam: b's lowest and highest values and their
|
||||
/// difference, in degrees (`angle`) or mm.
|
||||
fn lift_json(l: &MotionLink, angle: bool) -> Value {
|
||||
// A table that is not whole (a hand-edited file) moves nothing, and says so.
|
||||
if l.lift.len() != cam::CAM_SAMPLES {
|
||||
return Value::Null;
|
||||
}
|
||||
let unit = |v: f64| if angle { v.to_degrees() } else { v };
|
||||
let (lo, hi) = l.lift.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
let (lo, hi) = (unit(lo + l.offset), unit(hi + l.offset));
|
||||
json!({"min": lo, "max": hi, "rise": hi - lo, "unit": if angle { "deg" } else { "mm" }})
|
||||
}
|
||||
|
||||
/// A cam's profile: a sketch's closed profile (kept by its outer loop's curve ids, so the sketch's
|
||||
/// other profiles may change), or picked edges of the cam's bodies (kept in the component's
|
||||
/// coordinates with the edges' names).
|
||||
fn cam_profile(s: &Session, p: &Value, cmd: &str) -> Result<CamProfile> {
|
||||
let v = p.get("profile").ok_or_else(|| bad(cmd, "`profile` is required: {sketch: id|name} or {edges: [[x, y, z], …]}"))?;
|
||||
if let Some(sk) = v.get("sketch") {
|
||||
let sketch = super::features::sketch_id(s, Some(sk), cmd, "profile.sketch")?;
|
||||
let st = s.model.state();
|
||||
let solved =
|
||||
st.sketches.iter().find(|x| x.feature == sketch).ok_or_else(|| bad(cmd, "that sketch is not evaluated (it is after the marker?)"))?;
|
||||
let picked = match v.get("index") {
|
||||
None => cam::sketch_profile(solved, &[]),
|
||||
Some(i) => i.as_u64().and_then(|i| usize::try_from(i).ok()).and_then(|i| solved.profiles.get(i)),
|
||||
};
|
||||
let profile = picked.ok_or_else(|| bad(cmd, "the sketch has no such closed profile (an open curve makes none)"))?;
|
||||
return Ok(CamProfile::Sketch { sketch, curves: profile.outer_curves.clone() });
|
||||
}
|
||||
let Some(Value::Array(pts)) = v.get("edges") else {
|
||||
return Err(bad(cmd, "`profile` is {sketch: id|name} or {edges: [[x, y, z], …]}"));
|
||||
};
|
||||
if pts.is_empty() || pts.len() > cam::MAX_PROFILE_EDGES {
|
||||
return Err(bad(cmd, format!("pick 1 to {} edges", cam::MAX_PROFILE_EDGES)));
|
||||
}
|
||||
let world: Vec<Vec3> = pts.iter().map(vec3).collect::<Option<_>>().ok_or_else(|| bad(cmd, "`edges` are finite [x, y, z] points"))?;
|
||||
let occurrence = match v.get("occurrence") {
|
||||
Some(o) => occurrence_id(s, Some(o), cmd)?,
|
||||
None => world.first().and_then(|w| occurrence_at(s, *w)).ok_or_else(|| bad(cmd, "no body there"))?,
|
||||
};
|
||||
let t = if occurrence == 0 { solidcraft_doc::IDENTITY } else { joints::occurrence_world(&s.doc, occurrence) };
|
||||
let inv = solidcraft_doc::mat_inverse(&t).ok_or_else(|| bad(cmd, "occurrence transform"))?;
|
||||
let picks: Vec<Vec3> = world.iter().map(|w| solidcraft_doc::apply_point(&inv, *w)).collect();
|
||||
let comp = s.doc.occurrences.iter().find(|o| o.id == occurrence).map(|o| o.component).unwrap_or(0);
|
||||
let st = s.model.state();
|
||||
let bodies: Vec<&solidcraft_doc::ModelBody> = st.bodies.iter().filter(|b| s.doc.model_body_component(b) == comp).collect();
|
||||
// Each pick's edge name on the body whose edges pass nearest it.
|
||||
let names = picks
|
||||
.iter()
|
||||
.map(|q| {
|
||||
let near = |b: &&solidcraft_doc::ModelBody| {
|
||||
b.mesh()
|
||||
.edges
|
||||
.iter()
|
||||
.flat_map(|e| e.windows(2))
|
||||
.filter_map(|w| Some(q.dist_to_segment(*w.first()?, *w.get(1)?)))
|
||||
.fold(f64::MAX, f64::min)
|
||||
};
|
||||
bodies
|
||||
.iter()
|
||||
.min_by(|x, y| near(x).total_cmp(&near(y)))
|
||||
.and_then(|b| solidcraft_doc::naming::edge_names_at(b, &[*q]).into_iter().next())
|
||||
.unwrap_or_default()
|
||||
})
|
||||
.collect();
|
||||
Ok(CamProfile::Edges { occurrence, picks, names })
|
||||
couple(s, p, cmd, MotionLink { a, ia, b, ib, ratio: 1.0, offset: 0.0, coupling: Some(c) })
|
||||
}
|
||||
|
||||
/// Add a coupling's motion link, or put it in place of link `link`: its ratio worked out from its
|
||||
@@ -944,18 +802,14 @@ fn couple(s: &mut Session, p: &Value, cmd: &str, mut l: MotionLink) -> Result<Va
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(l.ratio, l.lift) =
|
||||
joints::coupling_values(&s.doc, &s.model.state(), &l).unwrap_or(Ok((l.ratio, Vec::new()))).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
l.ratio = joints::coupling_ratio(&s.doc, &s.model.state(), &l).unwrap_or(Ok(l.ratio)).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let vals = joints::joint_values(&s.doc.assembly);
|
||||
let value = |id: u64, i: usize| vals.get(&id).and_then(|q| q.get(i)).copied().unwrap_or(0.0);
|
||||
// A link put in place of another keeps its offset, as a radius edited in the design does.
|
||||
l.offset = match replace.and_then(|i| links.get(i)) {
|
||||
Some(old) => old.offset,
|
||||
None => value(l.b, l.ib) - MotionLink { offset: 0.0, ..l.clone() }.follow(value(l.a, l.ia)),
|
||||
None => value(l.b, l.ib) - l.ratio * value(l.a, l.ia),
|
||||
};
|
||||
if !l.offset.is_finite() {
|
||||
return Err(bad(cmd, "the coupling gives the driven joint no value where it is"));
|
||||
}
|
||||
let shown = l.ratio / ratio_scale(s, l.a, l.ia, l.b, l.ib);
|
||||
let doc = s.doc_mut();
|
||||
let index = match replace {
|
||||
@@ -1116,17 +970,10 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
json!({"a": l.a, "ia": l.ia, "b": l.b, "ib": l.ib, "ratio": ratio, "offset": offset, "unit": if angle { "deg" } else { "mm" }});
|
||||
if let Some(c) = &l.coupling {
|
||||
v["coupling"] = json!(c);
|
||||
if let Some(Err(e)) = joints::coupling_values(&s.doc, &st, l) {
|
||||
if let Some(Err(e)) = joints::coupling_ratio(&s.doc, &st, l) {
|
||||
v["error"] = json!(e.to_string());
|
||||
}
|
||||
}
|
||||
// A cam's follower follows its table, not a ratio: its travel instead.
|
||||
if matches!(l.coupling, Some(Coupling::Cam(_)))
|
||||
&& let Some(o) = v.as_object_mut()
|
||||
{
|
||||
o.remove("ratio");
|
||||
o.insert("lift".into(), lift_json(l, angle));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1,435 +0,0 @@
|
||||
//! Cams: a revolute joint drives a follower that rides the cam's profile. Expected values are
|
||||
//! analytic: an eccentric circle of radius R whose centre is e from its axis puts a knife-edge
|
||||
//! follower on a line h from the axis at e·cos θ + √(R² − (h − e·sin θ)²), a roller of radius r
|
||||
//! where a knife on the circle of radius R + r would be, a flat face at e·cos θ + R; an
|
||||
//! oscillating follower's roller sits where its arm's circle meets the circle of radius R + r.
|
||||
|
||||
use super::*;
|
||||
use solidcraft_doc::joints::Coupling;
|
||||
use solidcraft_doc::joints::cam::CamProfile;
|
||||
|
||||
/// The cam's eccentricity and radius (mm).
|
||||
const E: f64 = 10.0;
|
||||
const R: f64 = 30.0;
|
||||
|
||||
fn joint_id(s: &Session, name: &str) -> u64 {
|
||||
s.doc.assembly.joints.iter().find(|j| j.name == name).map(|j| j.id).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A joint's value as `joint.list` gives it (degrees or mm).
|
||||
fn shown(s: &mut Session, joint: &str) -> f64 {
|
||||
let l = run(s, "joint.list", json!({"quiet": true}));
|
||||
let j = l["joints"].as_array().into_iter().flatten().find(|j| j["name"] == joint).cloned().unwrap_or_default();
|
||||
j["values"][0]["value"].as_f64().unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// Where a knife edge on a line `h` from the axis stands on the circle of radius `r` about the
|
||||
/// cam's centre turned by `deg`.
|
||||
fn knife(deg: f64, h: f64, r: f64) -> f64 {
|
||||
let t = deg.to_radians();
|
||||
E * t.cos() + (r * r - (h - E * t.sin()).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
/// A grounded base, and a cam: a disc of radius `rc` (a parameter, 30 mm) about (10, 0), 5 mm thick,
|
||||
/// drawn in sketch `CamSketch` of its own component, on a revolute joint `Cam` about Z through the
|
||||
/// origin (the cam is its b side).
|
||||
fn cam_on_base() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "rc", "expression": "30 mm"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "th", "expression": "5 mm"}));
|
||||
part(&mut s, "Base", [-90.0, -90.0, -20.0]);
|
||||
let g = occ(&s, "Base");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Cam"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "CamSketch"}));
|
||||
run(&mut s, "sketch.circle.center", json!({"center": [E, 0], "radius": R, "id": "c1"}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["c1"], "type": "radius", "value": "rc"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.extrude", json!({"distance": "th"}));
|
||||
pin(&mut s, "revolute", "Cam", "Base", "Cam", Vec3::ZERO, Vec3::Z);
|
||||
s
|
||||
}
|
||||
|
||||
/// A tappet (a 20 mm bar, 4 wide) sliding along +X on the line y = `h`, its end at x = `tip`, on a
|
||||
/// slider `Tappet`.
|
||||
fn tappet(s: &mut Session, h: f64, tip: f64) {
|
||||
run(s, "component.activate", json!({"component": "root"}));
|
||||
run(s, "component.create", json!({"name": "Tappet"}));
|
||||
run(s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]}));
|
||||
pin(s, "slider", "Tappet", "Base", "Tappet", Vec3::new(0.0, h, 2.5), Vec3::X);
|
||||
}
|
||||
|
||||
fn close(got: f64, want: f64, tol: f64) -> bool {
|
||||
(got - want).abs() < tol
|
||||
}
|
||||
|
||||
/// A knife-edge tappet on the eccentric circle, its line through the axis and 6 mm past it, rises
|
||||
/// and falls as e·cos θ + √(R² − (h − e·sin θ)²); the tappet's body goes with it.
|
||||
#[test]
|
||||
fn a_knife_edge_tappet_rides_an_eccentric_circle() {
|
||||
for h in [0.0, 6.0] {
|
||||
let mut s = cam_on_base();
|
||||
let tip = knife(0.0, h, R);
|
||||
tappet(&mut s, h, tip);
|
||||
let r = run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
assert_eq!((r["link"].clone(), r["reverse"].clone()), (json!(0), json!(false)), "{r}");
|
||||
assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}");
|
||||
// It stays where it is, and its travel over a turn is the cam's.
|
||||
assert!(close(shown(&mut s, "Tappet"), 0.0, 1e-9), "{r}");
|
||||
let over_a_turn: Vec<f64> = (0..3600).map(|k| knife(f64::from(k) / 10.0, h, R)).collect();
|
||||
let rise = over_a_turn.iter().fold(f64::MIN, |a, b| a.max(*b)) - over_a_turn.iter().fold(f64::MAX, |a, b| a.min(*b));
|
||||
assert!(close(r["lift"]["rise"].as_f64().unwrap_or(f64::NAN), rise, 2e-3), "{r} vs {rise}");
|
||||
for deg in [30.0f64, 90.0, 135.0, 200.0, 300.0, -45.0, 400.0] {
|
||||
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
|
||||
let want = knife(deg, h, R) - tip;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "h {h} θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5));
|
||||
assert!(close(end.x, tip + want, 1e-3) && close(end.y, h, 1e-9), "{end:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The follower's line is through its tip, wherever its slider's origin is across the line; a
|
||||
/// guide of its own (grounded, the slider's b side) makes the tappet the slider's a side, and it
|
||||
/// rides the same way.
|
||||
#[test]
|
||||
fn a_tappet_on_a_guide_of_its_own_rides_its_tip_s_line() {
|
||||
let h = 6.0;
|
||||
let tip = knife(0.0, h, R);
|
||||
let mut s = cam_on_base();
|
||||
part(&mut s, "Guide", [70.0, 20.0, 0.0]);
|
||||
let g = occ(&s, "Guide");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": g, "grounded": true}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Tappet"}));
|
||||
run(&mut s, "solid.box", json!({"length": 20, "width": 4, "height": 5, "corner": [tip, h - 2.0, 0]}));
|
||||
// The slider's origins 9 mm across from the tappet's line, a the tappet, b the guide.
|
||||
pin(&mut s, "slider", "Tappet", "Tappet", "Guide", Vec3::new(0.0, h + 9.0, 2.5), Vec3::X);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"joint.cam",
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "tip": {"occurrence": "Tappet", "point": [tip, h, 2.5]}}),
|
||||
);
|
||||
assert!(close(r["follower_offset"].as_f64().unwrap_or(f64::NAN), h, 1e-9), "{r}");
|
||||
for deg in [70.0f64, 160.0, 290.0] {
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
let end = place(&s, "Tappet", Vec3::new(tip, h, 2.5));
|
||||
assert!(close(end.x, knife(deg, h, R), 1e-3), "θ {deg}: {end:?} vs {}", knife(deg, h, R));
|
||||
}
|
||||
}
|
||||
|
||||
/// A roller of radius 5 rides the circle of radius R + 5; a flat face e·cos θ + R, and when the
|
||||
/// cam's radius parameter grows by 2 the flat face stands 2 further out at every angle.
|
||||
#[test]
|
||||
fn rollers_and_flat_faces_ride_their_offset_circles() {
|
||||
let mut s = cam_on_base();
|
||||
let tip = knife(0.0, 0.0, R + 5.0);
|
||||
tappet(&mut s, 0.0, tip);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "5 mm"}));
|
||||
for deg in [60.0f64, 150.0, 250.0] {
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
let want = knife(deg, 0.0, R + 5.0) - tip;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "roller θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
let mut s = cam_on_base();
|
||||
tappet(&mut s, 3.0, E + R);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"}));
|
||||
for deg in [60.0f64, 150.0, 250.0] {
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
let want = E * deg.to_radians().cos() - E;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "flat θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
// Editing the profile: the table is worked out again.
|
||||
run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"}));
|
||||
let want = E * 250f64.to_radians().cos() - E + 2.0;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "after the edit: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
|
||||
/// The cam's top edge picked on its body gives the table its sketch gives, and follows the
|
||||
/// design the same way.
|
||||
#[test]
|
||||
fn picked_edges_give_the_sketch_s_table() {
|
||||
let table = |profile: Value| {
|
||||
let mut s = cam_on_base();
|
||||
tappet(&mut s, 0.0, E + R);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": profile}));
|
||||
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]]}));
|
||||
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.
|
||||
let mut s = cam_on_base();
|
||||
run(&mut s, "component.activate", json!({"component": "Cam"}));
|
||||
run(&mut s, "solid.cylinder", json!({"base": [E + R + 20.0, 0, 0], "axis": [0, 0, 1], "radius": 20, "height": 5}));
|
||||
tappet(&mut s, 0.0, E + R);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E - R, 0, 5]]}}));
|
||||
let touching = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
|
||||
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]]}}));
|
||||
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()))
|
||||
));
|
||||
run(&mut s, "parameters.change", json!({"name": "rc", "expression": "32 mm"}));
|
||||
// A thicker cam: the picked edge is found at its new height, and its loop with it.
|
||||
run(&mut s, "parameters.change", json!({"name": "th", "expression": "7 mm"}));
|
||||
let l = run(&mut s, "joint.list", json!({"quiet": true}));
|
||||
assert!(l["links"][0].get("error").is_none(), "{l}");
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90}));
|
||||
let want = knife(90.0, 0.0, 32.0) - (E + R);
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "{} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
|
||||
/// An arm of 50 about (−50, 40) with a roller of 5: its roller's centre is where the arm's circle
|
||||
/// meets the circle of radius R + 5 about the cam's centre, the meeting it turns into first from
|
||||
/// pointing away from the cam's axis.
|
||||
#[test]
|
||||
fn an_oscillating_roller_follower_swings_to_the_offset_circle() {
|
||||
let (pivot, arm, roller) = (Vec3::new(-50.0, 40.0, 2.5), 50.0, 5.0);
|
||||
let away = pivot.y.atan2(pivot.x);
|
||||
let wrap = |a: f64| (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;
|
||||
let angle = |p: Vec3| (p.y - pivot.y).atan2(p.x - pivot.x);
|
||||
// Where the roller's centre is at cam angle `deg`, turning the way `turn` says.
|
||||
let centre = |deg: f64, turn: f64| {
|
||||
let c = Vec3::new(E * deg.to_radians().cos(), E * deg.to_radians().sin(), 2.5);
|
||||
let [p, q] = meet(pivot, arm, c, R + roller);
|
||||
let swept = |x: Vec3| (turn * (angle(x) - away)).rem_euclid(std::f64::consts::TAU);
|
||||
if swept(p) < swept(q) { p } else { q }
|
||||
};
|
||||
let [p, q] = meet(pivot, arm, Vec3::new(E, 0.0, 2.5), R + roller);
|
||||
let start = if wrap(angle(p) - away).abs() < wrap(angle(q) - away).abs() { p } else { q };
|
||||
let turn = wrap(angle(start) - away).signum();
|
||||
let mut s = cam_on_base();
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Arm"}));
|
||||
run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 5, "corner": [start.x - 2.0, start.y - 2.0, 0]}));
|
||||
pin(&mut s, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z);
|
||||
// An oscillating follower needs its tip.
|
||||
assert!(s.execute("joint.cam", &json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5})).is_err());
|
||||
let r = run(
|
||||
&mut s,
|
||||
"joint.cam",
|
||||
json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 5,
|
||||
"tip": {"occurrence": "Arm", "point": [start.x, start.y, 2.5]}}),
|
||||
);
|
||||
assert_eq!((r["reverse"].clone(), r["lift"]["unit"].clone()), (json!(turn < 0.0), json!("deg")), "{r}");
|
||||
for deg in [40.0f64, 120.0, 210.0, 330.0] {
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
let want = wrap(angle(centre(deg, turn)) - angle(start)).to_degrees();
|
||||
assert!(close(shown(&mut s, "Arm"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Arm"));
|
||||
let at = place(&s, "Arm", start);
|
||||
assert!(at.dist(centre(deg, turn)) < 1e-3, "θ {deg}: {at:?}");
|
||||
}
|
||||
// The roller's round face picked on its arm is where it touches, and its radius: the same table.
|
||||
let table = s.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
|
||||
let mut t = cam_on_base();
|
||||
run(&mut t, "component.activate", json!({"component": "root"}));
|
||||
run(&mut t, "component.create", json!({"name": "Arm"}));
|
||||
run(&mut t, "solid.cylinder", json!({"base": [start.x, start.y, 0], "axis": [0, 0, 1], "radius": roller, "height": 5}));
|
||||
pin(&mut t, "revolute", "Arm", "Base", "Arm", pivot, Vec3::Z);
|
||||
let face = [start.x + roller, start.y, 2.5];
|
||||
run(
|
||||
&mut t,
|
||||
"joint.cam",
|
||||
json!({"a": "Cam", "b": "Arm", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": {"occurrence": "Arm", "circle": face}}),
|
||||
);
|
||||
let picked = t.doc.assembly.links.first().map(|l| l.lift.clone()).unwrap_or_default();
|
||||
assert!(picked.len() == 360 && picked.iter().zip(&table).all(|(x, y)| close(*x, *y, 1e-6)));
|
||||
}
|
||||
|
||||
/// A stationary cam: the profile on the grounded part, a rotor turning about it with the tappet's
|
||||
/// guide on it. Turned by +θ against the cam, the tappet stands where it would on a cam turned by
|
||||
/// −θ. A guide on the cam's own (grounded) side would turn with the profile: refused.
|
||||
#[test]
|
||||
fn a_stationary_cam_drives_a_follower_on_a_turning_rotor() {
|
||||
let h = 6.0;
|
||||
let tip = knife(0.0, h, R);
|
||||
let mut s = cam_on_base();
|
||||
// The cam is the fixed part: ground it, and take the base off its joint.
|
||||
let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base"));
|
||||
run(&mut s, "joint.delete", json!({"joint": "Cam"}));
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true}));
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false}));
|
||||
pin(&mut s, "revolute", "Turret", "Cam", "Base", Vec3::ZERO, Vec3::Z);
|
||||
tappet(&mut s, h, tip);
|
||||
run(&mut s, "joint.cam", json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
for deg in [50.0f64, 140.0, 260.0] {
|
||||
let d = run(&mut s, "joint.drive", json!({"joint": "Turret", "value": deg}));
|
||||
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
|
||||
let want = knife(-deg, h, R) - tip;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "θ {deg}: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
let mut s = cam_on_base();
|
||||
let (cam, base) = (occ(&s, "Cam"), occ(&s, "Base"));
|
||||
run(&mut s, "joint.delete", json!({"joint": "Cam"}));
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": cam, "grounded": true}));
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": false}));
|
||||
part(&mut s, "Rotor", [-90.0, 60.0, -20.0]);
|
||||
pin(&mut s, "revolute", "Turret", "Cam", "Rotor", Vec3::ZERO, Vec3::Z);
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true}));
|
||||
tappet(&mut s, h, tip);
|
||||
let e = s.execute("joint.cam", &json!({"a": "Turret", "b": "Tappet", "profile": {"sketch": "CamSketch"}})).map_err(|e| e.to_string()).err();
|
||||
assert!(e.as_deref().is_some_and(|e| e.contains("turns with the cam")), "{e:?}");
|
||||
}
|
||||
|
||||
/// A motion study turning the cam plays the tappet through its analytic travel.
|
||||
#[test]
|
||||
fn a_cam_plays_in_a_motion_study() {
|
||||
let mut s = cam_on_base();
|
||||
let tip = knife(0.0, 0.0, R);
|
||||
tappet(&mut s, 0.0, tip);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
run(&mut s, "motion.study", json!({"name": "Turn", "steps": 10, "keys": [{"joint": "Cam", "points": [[0, 0], [10, 360]]}]}));
|
||||
for step in [0, 2, 5, 7, 10] {
|
||||
run(&mut s, "motion.play", json!({"study": "Turn", "step": step}));
|
||||
let want = knife(36.0 * f64::from(step), 0.0, R) - tip;
|
||||
assert!(close(shown(&mut s, "Tappet"), want, 1e-3), "step {step}: {} vs {want}", shown(&mut s, "Tappet"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The tappet is the piston of a slider-crank: a 40 mm rod from its end to a 20 mm crank about
|
||||
/// (95, 0). Turning the cam moves the tappet, and the loop turns the crank to where the rod's
|
||||
/// circle meets the crank's, on the branch it started on. A stop in a contact set with the cam and
|
||||
/// the tappet halts the cam where the tappet reaches it; the cam and the flat tappet only touch.
|
||||
#[test]
|
||||
fn a_cam_drives_a_closed_loop_and_stops_at_a_contact() {
|
||||
let mut s = cam_on_base();
|
||||
let tip = knife(0.0, 0.0, R);
|
||||
tappet(&mut s, 0.0, tip);
|
||||
let (q, end) = (Vec3::new(95.0, 0.0, 2.5), Vec3::new(tip + 20.0, 0.0, 2.5));
|
||||
let crank_pin = |x: f64| meet(q, 20.0, Vec3::new(x, 0.0, 2.5), 40.0).into_iter().find(|p| p.y > 0.0).unwrap_or(Vec3::ZERO);
|
||||
let pin0 = crank_pin(end.x);
|
||||
for (name, at) in [("Rod", end), ("Crank", pin0)] {
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": name}));
|
||||
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [at.x - 1.0, at.y - 1.0, 10]}));
|
||||
}
|
||||
pin(&mut s, "revolute", "Crank", "Base", "Crank", q, Vec3::Z);
|
||||
pin(&mut s, "revolute", "Wrist", "Tappet", "Rod", end, Vec3::Z);
|
||||
pin(&mut s, "revolute", "Big end", "Rod", "Crank", pin0, Vec3::Z);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
for deg in [45.0f64, 120.0, 180.0] {
|
||||
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": deg}));
|
||||
assert_eq!(d["conflicts"].as_array().map(Vec::len), Some(0), "{d}");
|
||||
let x = end.x + knife(deg, 0.0, R) - tip;
|
||||
let at = place(&s, "Crank", pin0);
|
||||
assert!(at.dist(crank_pin(x)) < 1e-3, "θ {deg}: {at:?} vs {:?}", crank_pin(x));
|
||||
}
|
||||
// A flat tappet, a stop 5 mm past where its end is at the top, and contact on.
|
||||
let mut s = cam_on_base();
|
||||
tappet(&mut s, 0.0, E + R);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "flat"}));
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 180}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Stop"}));
|
||||
run(&mut s, "solid.box", json!({"length": 3, "width": 4, "height": 5, "corner": [E + R + 15.0, -2, 0]}));
|
||||
let st = occ(&s, "Stop");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": st, "grounded": true}));
|
||||
run(&mut s, "contact.create", json!({"occurrences": ["Cam", "Tappet", "Stop"]}));
|
||||
// Touching the cam stops nothing: half a turn moves the tappet 20 mm back up, as far as the stop.
|
||||
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 90}));
|
||||
assert!(d["stopped_by_contact"].is_null(), "{d}");
|
||||
let d = run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 0}));
|
||||
assert!(d["stopped_by_contact"].is_object(), "{d}");
|
||||
let reached = shown(&mut s, "Tappet");
|
||||
assert!(reached > -5.5 && reached < -4.5, "{reached}");
|
||||
}
|
||||
|
||||
/// What a cam can't be made from is refused, and a table edited by hand never puts a NaN into a
|
||||
/// joint's value.
|
||||
#[test]
|
||||
fn hostile_cams_are_refused() {
|
||||
let mut s = cam_on_base();
|
||||
tappet(&mut s, 0.0, E + R);
|
||||
let refused = |s: &mut Session, p: Value| s.execute("joint.cam", &p).map_err(|e| e.to_string()).err().unwrap_or_else(|| panic!("accepted {p}"));
|
||||
// An open curve makes no closed profile.
|
||||
run(&mut s, "component.activate", json!({"component": "Cam"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Open"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [20, 5], [10, 20]]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "Open"}}));
|
||||
assert!(e.contains("closed profile"), "{e}");
|
||||
// Two closed edges are not one loop; a line past the cam misses it.
|
||||
let e = refused(&mut s, json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[E + R, 0, 5], [E + R, 0, 0]]}}));
|
||||
assert!(e.contains("closed loop"), "{e}");
|
||||
let mut far = cam_on_base();
|
||||
tappet(&mut far, 50.0, 0.0);
|
||||
let e = refused(&mut far, json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
assert!(e.contains("misses"), "{e}");
|
||||
for p in [
|
||||
json!({"a": "Tappet", "b": "Cam", "profile": {"sketch": "CamSketch"}}),
|
||||
json!({"a": "Cam", "b": "Cam", "profile": {"sketch": "CamSketch"}}),
|
||||
json!({"a": "Cam", "b": "Tappet"}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch", "index": 7}}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": []}}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": [[1, "x", 0]]}}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"edges": vec![[E + R, 0.0, 5.0]; 65]}}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller"}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": -1}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": "nope"}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 1e300}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "spring"}),
|
||||
json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "link": 3}),
|
||||
] {
|
||||
refused(&mut s, p);
|
||||
}
|
||||
assert!(s.doc.assembly.links.is_empty());
|
||||
// A table edited by hand: NaN leaves the follower where it is, any length reads.
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}}));
|
||||
let before = solidcraft_doc::joints::joint_values(&s.doc.assembly);
|
||||
for lift in [vec![f64::NAN; 360], vec![1.0, 2.0, 3.0], vec![f64::INFINITY]] {
|
||||
let mut d = (*s.doc).clone();
|
||||
if let Some(l) = d.assembly.links.first_mut() {
|
||||
l.lift = lift;
|
||||
}
|
||||
let vals = solidcraft_doc::joints::joint_values(&d.assembly);
|
||||
assert!(vals.values().flatten().all(|v| v.is_finite()), "{vals:?}");
|
||||
// The follower keeps where it is.
|
||||
assert_eq!(vals.get(&joint_id(&s, "Tappet")), d.assembly.joints.iter().find(|j| j.name == "Tappet").map(|j| &j.values), "{before:?}");
|
||||
}
|
||||
// A table on a plain link is not read.
|
||||
let mut d = (*s.doc).clone();
|
||||
if let Some(l) = d.assembly.links.first_mut() {
|
||||
(l.coupling, l.ratio, l.offset) = (None, 0.0, 3.0);
|
||||
}
|
||||
assert_eq!(solidcraft_doc::joints::joint_values(&d.assembly).get(&joint_id(&s, "Tappet")).and_then(|q| q.first()).copied(), Some(3.0));
|
||||
// A roller's picked face must turn about an axis parallel to the cam's, a tip given or not.
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Pin"}));
|
||||
run(&mut s, "solid.cylinder", json!({"base": [60, 30, 0], "axis": [1, 0, 0], "radius": 3, "height": 10}));
|
||||
run(&mut s, "joint.delete", json!({"link": 0}));
|
||||
let tilted = json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller",
|
||||
"radius": {"occurrence": "Pin", "circle": [65, 33, 0]}, "tip": {"occurrence": "Tappet", "point": [E + R, 0, 2.5]}});
|
||||
let e = refused(&mut s, tilted);
|
||||
assert!(e.contains("roller's axis"), "{e}");
|
||||
}
|
||||
|
||||
/// A cam saves and opens with its definition and table; a link saved before cams reads as a
|
||||
/// plain link.
|
||||
#[test]
|
||||
fn cams_save_and_open_with_their_table() {
|
||||
let mut s = cam_on_base();
|
||||
tappet(&mut s, 0.0, E + R);
|
||||
run(&mut s, "joint.cam", json!({"a": "Cam", "b": "Tappet", "profile": {"sketch": "CamSketch"}, "follower": "roller", "radius": 2}));
|
||||
run(&mut s, "joint.drive", json!({"joint": "Cam", "value": 30}));
|
||||
let text = s.doc.to_json();
|
||||
let back = solidcraft_doc::format::read(&text).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(back.assembly.links, s.doc.assembly.links);
|
||||
assert_eq!(back.assembly.links.first().map(|l| l.lift.len()), Some(360));
|
||||
let l = run(&mut s, "joint.list", json!({}));
|
||||
let link = &l["links"][0];
|
||||
assert!(link.get("ratio").is_none() && link["lift"]["unit"] == "mm" && link["coupling"]["type"] == "cam", "{link}");
|
||||
assert!(link["coupling"].get("lift").is_none(), "{link}");
|
||||
let mut v: Value = serde_json::from_str(&text).unwrap_or_default();
|
||||
for l in v["assembly"]["links"].as_array_mut().into_iter().flatten() {
|
||||
l.as_object_mut().map(|o| (o.remove("coupling"), o.remove("lift")));
|
||||
}
|
||||
let old = solidcraft_doc::format::read(&v.to_string()).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(old.assembly.links.iter().all(|l| l.coupling.is_none() && l.lift.is_empty()));
|
||||
}
|
||||
@@ -34,40 +34,6 @@ fn leaf(s: &mut Session, name: &str) {
|
||||
run(s, "solid.cylinder", json!({"base": [0, 33, 4], "axis": [1, 0, 0], "radius": 4, "height": 40, "operation": "new"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circle_given_by_its_centre_takes_that_round_end() {
|
||||
// #393: `circle` at the centre of a round end, as the parameters document, was refused with
|
||||
// "no cylindrical face there" (no face lies at a centre).
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "component.create", json!({"name": "Plate"}));
|
||||
run(&mut s, "solid.box", json!({"length": 30, "width": 20, "height": 6, "corner": [-15, -10, 0]}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": "Knob"}));
|
||||
run(&mut s, "solid.cylinder", json!({"base": [0, 0, 6], "axis": [0, 0, 1], "radius": 10, "height": 10, "operation": "new"}));
|
||||
let r = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({"type": "cylindrical", "a": {"occurrence": "Plate", "face": [0, 0, 6]}, "b": {"occurrence": "Knob", "circle": [0, 0, 6]}, "name": "J"}),
|
||||
);
|
||||
assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}");
|
||||
// The knob's bottom circle already sits on the plate's top: its axis stays put (it may turn
|
||||
// about it, to line up the two frames' x).
|
||||
for z in [6.0, 16.0] {
|
||||
assert!(near(place(&s, "Knob", Vec3::new(0.0, 0.0, z)), Vec3::new(0.0, 0.0, z)), "{:?}", place(&s, "Knob", Vec3::new(0.0, 0.0, z)));
|
||||
}
|
||||
// The top end's centre: its axis points up, out of the knob.
|
||||
run(&mut s, "joint.origin", json!({"occurrence": "Knob", "circle": [0, 0, 16], "name": "Top"}));
|
||||
let top = s.doc.assembly.origins.iter().find(|o| o.name == "Top").map(|o| o.origin.snap.clone());
|
||||
assert!(
|
||||
matches!(top, Some(solidcraft_doc::joints::Snap::Point { point, z: Some(z) }) if near(point, Vec3::new(0.0, 0.0, 16.0)) && near(z, Vec3::Z)),
|
||||
"{top:?}"
|
||||
);
|
||||
// Off the axis is still refused, and so is a coupling size (it follows a face).
|
||||
assert!(s.execute("joint.origin", &json!({"occurrence": "Knob", "circle": [3, 0, 6]})).is_err());
|
||||
let e = s.execute("joint.screw", &json!({"joint": "J", "pitch": {"occurrence": "Knob", "circle": [0, 0, 6]}})).unwrap_err();
|
||||
assert!(e.to_string().contains("not its centre"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revolute_hinge_turns_about_the_knuckle() {
|
||||
let mut s = Session::default();
|
||||
@@ -1445,10 +1411,3 @@ fn hostile_trace_params_are_refused() {
|
||||
|
||||
#[path = "joints_coupling_tests.rs"]
|
||||
mod coupling;
|
||||
|
||||
#[path = "joints_cam_tests.rs"]
|
||||
mod cam;
|
||||
|
||||
// Plots and interference of motion studies, on the four-bar and slider-crank above.
|
||||
#[path = "motion_analysis_tests.rs"]
|
||||
mod motion_analysis;
|
||||
@@ -309,6 +309,7 @@ fn every_flat_face_of_a_block_and_a_flush_step_takes_a_sketch() {
|
||||
/// #681 as reported: one sketch of a 2 x 2 grid, three cells extruded up (an elbow) and three
|
||||
/// joined down (the inverse elbow).
|
||||
#[test]
|
||||
#[ignore = "the join of the elbow down fails until #679 is fixed"]
|
||||
fn every_flat_face_of_an_elbow_up_and_an_elbow_down_takes_a_sketch() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Grid"}));
|
||||
@@ -326,76 +327,3 @@ fn every_flat_face_of_an_elbow_up_and_an_elbow_down_takes_a_sketch() {
|
||||
);
|
||||
every_flat_face_takes_a_sketch(&mut s);
|
||||
}
|
||||
|
||||
/// #565: Split Body by a plane a parameter moves (a raw plane, a construction plane or a sketch
|
||||
/// line). The face the split cuts on each part is named after the half-space that cut it
|
||||
/// (`F<split>:section`): a sketch and an offset plane attach to it and follow the plane.
|
||||
#[test]
|
||||
fn the_face_a_split_cuts_takes_a_sketch_and_an_offset_plane_that_follow_the_plane() {
|
||||
for tool in ["plane", "construction", "line"] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "split_x", "expression": "15 mm"}));
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 20, "height": 10, "body_name": "Block"}));
|
||||
let split = match tool {
|
||||
"plane" => json!({"body": "Block", "plane": {"origin": ["split_x", 0, 0], "normal": [1, 0, 0]}}),
|
||||
"construction" => {
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "YZ", "offset": "split_x", "name": "Cut"}));
|
||||
json!({"body": "Block", "plane": "Cut"})
|
||||
}
|
||||
_ => {
|
||||
let id = run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Guide"}))["sketch"].as_u64().unwrap();
|
||||
run(&mut s, "sketch.line", json!({"points": [[15, -10], [15, 30]], "ids": ["cut"], "connect": false}));
|
||||
run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "cut", "mode": "vertical"}));
|
||||
run(&mut s, "sketch.dimension", json!({"entities": ["origin", "cut.start"], "type": "horizontal", "value": "split_x"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
json!({"body": "Block", "sketch": id, "line": "cut"})
|
||||
}
|
||||
};
|
||||
run(&mut s, "solid.split_body", split);
|
||||
no_errors(&s);
|
||||
// Each part's cut face (the two lie on one another, so each is picked by body and index).
|
||||
let cut_face = |s: &Session, body: &str, x: f64| {
|
||||
let state = s.model.state();
|
||||
let b = &state.body(body).unwrap().body;
|
||||
let index = (0..b.face_count())
|
||||
.find(|i| b.planar_face(*i).is_some_and(|p| p.normal().x.abs() > 0.999 && (p.origin.x - x).abs() < 1e-9))
|
||||
.unwrap_or_else(|| panic!("{tool}: no cut face on `{body}`"));
|
||||
json!({"face": [x, 10, 5], "body": body, "index": index})
|
||||
};
|
||||
let mut normals = Vec::new();
|
||||
for (k, body) in ["Block", "Block (1)"].into_iter().enumerate() {
|
||||
let pick = cut_face(&s, body, 15.);
|
||||
run(&mut s, "sketch.create", json!({"plane": pick, "name": format!("OnCut{k}")}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
let (plane, certificate) = healthy(&s, &format!("OnCut{k}"));
|
||||
assert_eq!(certificate, Some(FaceCertificate::Lineage), "{tool} {body}");
|
||||
assert!((plane.origin.x - 15.).abs() < 1e-9 && plane.normal().x.abs() > 0.999, "{tool} {body}: {plane:?}");
|
||||
normals.push(plane.normal().x);
|
||||
let pick = cut_face(&s, body, 15.);
|
||||
run(&mut s, "construct.plane.offset", json!({"base": pick, "offset": 2, "name": format!("Off{k}")}));
|
||||
}
|
||||
assert!(normals[0] * normals[1] < 0., "{tool}: the two cut faces face each other's way: {normals:?}");
|
||||
no_errors(&s);
|
||||
|
||||
run(&mut s, "parameters.change", json!({"name": "split_x", "expression": "20 mm"}));
|
||||
no_errors(&s);
|
||||
let offset = |s: &Session, name: &str| {
|
||||
let feature = s.doc.find_feature(name).map(|f| f.id).unwrap();
|
||||
let state = s.model.state();
|
||||
match state.construct.iter().find(|c| c.feature == feature).map(|c| &c.geom) {
|
||||
Some(solidcraft_doc::construct::ConstructGeom::Plane(p)) => *p,
|
||||
other => panic!("{tool} {name}: {other:?}"),
|
||||
}
|
||||
};
|
||||
for (k, n) in normals.iter().enumerate() {
|
||||
let (plane, _) = healthy(&s, &format!("OnCut{k}"));
|
||||
assert!((plane.origin.x - 20.).abs() < 1e-9 && (plane.normal().x - n).abs() < 1e-9, "{tool} OnCut{k}: {plane:?}");
|
||||
let off = offset(&s, &format!("Off{k}"));
|
||||
assert!((off.origin.x - (20. + 2. * n)).abs() < 1e-9, "{tool} Off{k}: {off:?}");
|
||||
}
|
||||
let t = reopened(&s);
|
||||
for k in 0..2 {
|
||||
assert!((healthy(&t, &format!("OnCut{k}")).0.origin.x - 20.).abs() < 1e-9, "{tool} reopened OnCut{k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ mod edit;
|
||||
mod face;
|
||||
mod features;
|
||||
mod features_more;
|
||||
pub use features::{auto_operation, extrude_reach};
|
||||
pub use features::auto_operation;
|
||||
mod component_link;
|
||||
mod config;
|
||||
mod file;
|
||||
@@ -74,7 +74,6 @@ mod sketch_modify;
|
||||
mod sketch_project;
|
||||
mod surface;
|
||||
mod surface_analysis;
|
||||
mod surface_boundary;
|
||||
mod surface_match;
|
||||
mod view_dxf;
|
||||
mod view_navigation;
|
||||
@@ -237,7 +236,6 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
|
||||
v.extend(sketch_canvas::COMMANDS.iter());
|
||||
v.extend(sketch_3d::COMMANDS.iter());
|
||||
v.extend(surface_analysis::COMMANDS.iter());
|
||||
v.extend(surface_boundary::COMMANDS.iter());
|
||||
v.extend(surface::COMMANDS.iter());
|
||||
v.extend(surface_match::COMMANDS.iter());
|
||||
v.extend(sketch_modify::COMMANDS.iter());
|
||||
|
||||
@@ -14,10 +14,6 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, reso
|
||||
use crate::params::{bad, bool_, str_, vec3};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
#[path = "motion_analysis.rs"]
|
||||
mod analysis;
|
||||
#[path = "motion_animation.rs"]
|
||||
mod animation;
|
||||
#[path = "contact_sweep.rs"]
|
||||
mod contact_sweep;
|
||||
|
||||
@@ -58,9 +54,6 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("motion.export", "Export Motion Study", export)
|
||||
.noundo()
|
||||
.params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"),
|
||||
CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).noundo().params(
|
||||
"study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?; path: a .gif file, or a folder for PNG frames (frame-0001.png, frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, or 100); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's axes) - draws the study as it plays, or the joint as it is driven, with the headless renderer → path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the design is not changed)",
|
||||
),
|
||||
CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!(
|
||||
trace_doc!(),
|
||||
" → points: [[x,y,z]…] world positions, samples (taken), stopped_at (the sample where the motion stopped short; the trace \
|
||||
@@ -71,8 +64,6 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"; name? (default Motion TraceN) - keeps the trace as a 3D sketch spline through its points (a new sketch with 3D Sketch \
|
||||
on, in the root component, where no joint moves it; a fixed curve, it does not follow later changes) → sketch, name, curves, points"
|
||||
)),
|
||||
CommandSpec::new("motion.plot", "Plot Motion Study", analysis::plot).noundo().params(analysis::PLOT_DOC),
|
||||
CommandSpec::new("motion.interference", "Motion Interference", analysis::interference).noundo().params(analysis::INTERFERENCE_DOC),
|
||||
CommandSpec::new("motion.list", "List Motion Studies", list_studies).noundo(),
|
||||
CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).params("study"),
|
||||
CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("joint").params(
|
||||
@@ -476,15 +467,12 @@ fn check(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
// ---- Motion studies ----
|
||||
|
||||
fn study_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
|
||||
// A number is an id first, text a name first: a study may be named like another's id.
|
||||
let (key, id_first) = match p.get("study") {
|
||||
Some(Value::Number(n)) => (n.to_string(), true),
|
||||
Some(Value::String(x)) => (x.clone(), false),
|
||||
let key = match p.get("study") {
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
Some(Value::String(x)) => x.clone(),
|
||||
_ => return Err(bad(cmd, "`study` must be an id or a name")),
|
||||
};
|
||||
let studies = &s.doc.assembly.studies;
|
||||
let (by_id, by_name) = (studies.iter().position(|m| m.id.to_string() == key), studies.iter().position(|m| m.name == key));
|
||||
if id_first { by_id.or(by_name) } else { by_name.or(by_id) }.ok_or_else(|| bad(cmd, format!("no motion study `{key}`")))
|
||||
s.doc.assembly.studies.iter().position(|m| m.id.to_string() == key || m.name == key).ok_or_else(|| bad(cmd, format!("no motion study `{key}`")))
|
||||
}
|
||||
|
||||
fn study(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -695,11 +683,13 @@ const MAX_TRACE: usize = solidcraft_sketch::MAX_FIT_POINTS;
|
||||
/// The joint values a trace drives to at sample `k` of `n`.
|
||||
type Plan = Box<dyn Fn(&Session, usize, usize) -> Vec<(u64, Vec<f64>)>>;
|
||||
|
||||
/// The point `p` names (`occurrence` and `point`): the occurrence path placing it and the point
|
||||
/// in that placement's frame. The occurrence is an occurrence path through nested sub-assemblies
|
||||
/// (one instance of each), or an occurrence at its first placement (none: the root). The point
|
||||
/// is a world point where the parts are placed (moves only shown are left out).
|
||||
fn traced_point(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<u64>, Vec3)> {
|
||||
/// Where a point of an occurrence goes as a study plays or a joint is driven: its world
|
||||
/// positions, sampled on a copy (the design is not changed). Each sample is driven from the one
|
||||
/// before, so closed loops follow on their branch and contact sets stop them; the trace ends at
|
||||
/// the sample where the motion stops short. Returns the points and the answer without them.
|
||||
fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Vec3>, Value)> {
|
||||
// The placement traced: an occurrence path through nested sub-assemblies (one instance of
|
||||
// each), or an occurrence at its first placement (none: the root).
|
||||
let path: Vec<u64> = match p.get("occurrence") {
|
||||
Some(Value::Array(ids)) if ids.len() <= 64 => {
|
||||
ids.iter().map(|v| v.as_u64().ok_or_else(|| bad(cmd, "an occurrence path lists occurrence ids"))).collect::<Result<_>>()?
|
||||
@@ -715,68 +705,32 @@ fn traced_point(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<u64>, Vec3)> {
|
||||
};
|
||||
let at = p.get("point").and_then(vec3).filter(|v| v.len() < 1e7).ok_or_else(|| bad(cmd, "`point` must be [x, y, z], a world point"))?;
|
||||
let mut t = s.scratch();
|
||||
t.pending_moves.clear();
|
||||
let local = solidcraft_doc::mat_inverse(&path_world(&t, &path, cmd)?)
|
||||
.map(|m| solidcraft_doc::apply_point(&m, at))
|
||||
.ok_or_else(|| bad(cmd, "the occurrence's placement is not invertible"))?;
|
||||
Ok((path, local))
|
||||
}
|
||||
|
||||
/// The world placement of an occurrence path (empty: the root).
|
||||
fn path_world(t: &Session, path: &[u64], cmd: &str) -> Result<Mat> {
|
||||
if path.is_empty() { Ok(solidcraft_doc::IDENTITY) } else { t.occurrence_placement(path).map(|o| o.world).map_err(|e| bad(cmd, e.to_string())) }
|
||||
}
|
||||
|
||||
/// Where a point of an occurrence goes as a study plays or a joint is driven: its world
|
||||
/// positions, sampled on a copy (the design is not changed). Each sample is driven from the one
|
||||
/// before, so closed loops follow on their branch and contact sets stop them; the trace ends at
|
||||
/// the sample where the motion stops short. Returns the points and the answer without them.
|
||||
fn sample_trace(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<Vec3>, Value)> {
|
||||
let (path, local) = traced_point(s, p, cmd)?;
|
||||
let mut t = s.scratch();
|
||||
// Traced from where the parts are placed: moves only shown (an exploded view, a move not
|
||||
// captured yet) are not where the joints are solved.
|
||||
t.pending_moves.clear();
|
||||
let world = |t: &Session| path_world(t, &path, cmd);
|
||||
let (default, given, plan) = motion_plan(s, p, cmd)?;
|
||||
let n = sample_count(p, default.min(MAX_TRACE), MAX_TRACE, cmd)?;
|
||||
let mut points = Vec::new();
|
||||
let mut stop = (Value::Null, Value::Null, Value::Null);
|
||||
for k in 0..n {
|
||||
let want = plan(&t, k, n);
|
||||
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
|
||||
points.push(solidcraft_doc::apply_point(&world(&t)?, local));
|
||||
if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() {
|
||||
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
|
||||
break;
|
||||
let world = |t: &Session| -> Result<Mat> {
|
||||
if path.is_empty() {
|
||||
Ok(solidcraft_doc::IDENTITY)
|
||||
} else {
|
||||
t.occurrence_placement(&path).map(|o| o.world).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
}
|
||||
let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone());
|
||||
let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2});
|
||||
Ok((points, out))
|
||||
}
|
||||
|
||||
/// `samples`, 2…`max`, or `default` without it.
|
||||
fn sample_count(p: &Value, default: usize, max: usize, cmd: &str) -> Result<usize> {
|
||||
match p.get("samples") {
|
||||
};
|
||||
let local = solidcraft_doc::mat_inverse(&world(&t)?)
|
||||
.map(|m| solidcraft_doc::apply_point(&m, at))
|
||||
.ok_or_else(|| bad(cmd, "the occurrence's placement is not invertible"))?;
|
||||
let samples = |default: usize| match p.get("samples") {
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && *n >= 2.0 && *n <= max as f64)
|
||||
.filter(|n| n.is_finite() && *n >= 2.0 && *n <= MAX_TRACE as f64)
|
||||
.map(|n| n.round() as usize)
|
||||
.ok_or_else(|| bad(cmd, format!("`samples` must be 2…{max}"))),
|
||||
None => Ok(default.max(2)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The motion a trace or an animation samples: a study played from start to end, or one joint
|
||||
/// value driven from `from` to `to`. Returns the default sample count (the study's steps + 1, or
|
||||
/// 100), the values driven and what they are at sample `k` of `n`.
|
||||
fn motion_plan(s: &Session, p: &Value, cmd: &str) -> Result<(usize, BTreeSet<(u64, usize)>, Plan)> {
|
||||
Ok(match (p.get("study"), p.get("joint")) {
|
||||
.ok_or_else(|| bad(cmd, format!("`samples` must be 2…{MAX_TRACE}"))),
|
||||
None => Ok(default),
|
||||
};
|
||||
let (n, given, plan): (usize, BTreeSet<(u64, usize)>, Plan) = match (p.get("study"), p.get("joint")) {
|
||||
(Some(_), Some(_)) => return Err(bad(cmd, "give `study` or `joint`, not both")),
|
||||
(Some(_), None) => {
|
||||
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
|
||||
let n = (m.steps as usize).saturating_add(1);
|
||||
let n = samples((m.steps as usize).saturating_add(1).clamp(2, MAX_TRACE))?;
|
||||
(n, keyed(&m), Box::new(move |t, k, n| values_at(t, &m, f64::from(m.steps) * k as f64 / (n - 1) as f64)))
|
||||
}
|
||||
(None, Some(j)) => {
|
||||
@@ -796,7 +750,7 @@ fn motion_plan(s: &Session, p: &Value, cmd: &str) -> Result<(usize, BTreeSet<(u6
|
||||
};
|
||||
let end = |key: &str| match p.get(key) {
|
||||
Some(v) => value(s, v, kind.is_angle(index), cmd),
|
||||
None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the motion runs between (no `{key}`)"))),
|
||||
None => Err(bad(cmd, format!("give `from` and `to`: the joint's values the trace runs between (no `{key}`)"))),
|
||||
};
|
||||
let (from, to) = (end("from")?, end("to")?);
|
||||
let plan: Plan = Box::new(move |t, k, n| {
|
||||
@@ -807,10 +761,24 @@ fn motion_plan(s: &Session, p: &Value, cmd: &str) -> Result<(usize, BTreeSet<(u6
|
||||
}
|
||||
vec![(id, q)]
|
||||
});
|
||||
(100, BTreeSet::from([(id, index)]), plan)
|
||||
(samples(100)?, BTreeSet::from([(id, index)]), plan)
|
||||
}
|
||||
(None, None) => return Err(bad(cmd, "give a `study`, or a `joint` with `from` and `to`")),
|
||||
})
|
||||
};
|
||||
let mut points = Vec::new();
|
||||
let mut stop = (Value::Null, Value::Null, Value::Null);
|
||||
for k in 0..n {
|
||||
let want = plan(&t, k, n);
|
||||
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
|
||||
points.push(solidcraft_doc::apply_point(&world(&t)?, local));
|
||||
if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() {
|
||||
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == path.last()).map_or_else(|| "root".to_string(), |o| o.name.clone());
|
||||
let out = json!({"occurrence": name, "samples": points.len(), "stopped_at": stop.0, "stopped_by_loop": stop.1, "stopped_by_contact": stop.2});
|
||||
Ok((points, out))
|
||||
}
|
||||
|
||||
fn trace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -1,456 +0,0 @@
|
||||
//! Motion analysis: a study played sample by sample on a copy of the design, the way
|
||||
//! `motion.play` places it (closed loops following on their branch). `motion.plot` answers the
|
||||
//! 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 std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::joints;
|
||||
use solidcraft_doc::motion::MotionStudy;
|
||||
use solidcraft_doc::{Document, Mat, apply_point, mat_mul};
|
||||
use solidcraft_geom::{Aabb3, Vec3};
|
||||
|
||||
use super::contact_sweep::{ContactGeometry, Member};
|
||||
use super::{drive_with_contact, joint_id, keyed, occurrences, path_world, study_index, traced_point, values_at};
|
||||
use crate::params::{bad, bool_};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub const PLOT_DOC: &str = "study: id|name; joints?: [id|name] (default: every joint that moves); occurrence? and point? (a point \
|
||||
of a part to follow, as motion.trace takes them); samples? (3…1000, default the study's steps + 1); duration?: seconds the \
|
||||
whole study takes, 0.001 or more (velocities and accelerations then per second, else per step) → step: [the study step of each sample], \
|
||||
time?: [s], joints: [{joint, name, index, dof, unit, value, velocity, acceleration, velocity_unit, acceleration_unit}] \
|
||||
(degrees for angles, mm for distances; angles unwrapped), point?: {occurrence, position: [[x,y,z]…], velocity, \
|
||||
acceleration (vectors), speed, acceleration_norm, unit, velocity_unit, acceleration_unit}, samples (taken), stopped_at, \
|
||||
stopped_by_loop, stopped_by_contact. The study plays as motion.play plays it, each sample driven from the one before, on \
|
||||
a copy (the design is not changed); velocities and accelerations are finite differences between samples (central, \
|
||||
one-sided at the ends)";
|
||||
|
||||
pub const INTERFERENCE_DOC: &str = "study: id|name; occurrences?: [ids or names] (two or more, checked against each other; \
|
||||
default every occurrence), with against?: [ids or names] (then each of `occurrences` is checked only against these, such \
|
||||
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) → 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, \
|
||||
pairs (checked), samples (taken), truncated (the work budget ran out; checked_to: the last step checked), 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 \
|
||||
changed). Parts are tested at the samples only: one that passes wholly through another between two samples is missed";
|
||||
|
||||
/// Most samples a plot or an interference check takes: each is a solve.
|
||||
const MAX_SAMPLES: usize = 1000;
|
||||
/// Most joint values one plot answers.
|
||||
const MAX_SERIES: usize = 256;
|
||||
/// Most collision work over a whole study (see `ContactGeometry::hits`).
|
||||
const MAX_WORK: usize = 500_000_000;
|
||||
/// Most colliding pairs whose overlap volume is worked out, and most body booleans that takes.
|
||||
const MAX_VOLUMES: usize = 16;
|
||||
const MAX_BOOLEANS: usize = 64;
|
||||
|
||||
/// 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<usize> {
|
||||
if m.steps == 0 {
|
||||
return Err(bad(cmd, "the study has no steps"));
|
||||
}
|
||||
match p.get("samples") {
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && *n >= min as f64 && *n <= MAX_SAMPLES as f64)
|
||||
.map(|n| n.round() as usize)
|
||||
.ok_or_else(|| bad(cmd, format!("`samples` must be {min}…{MAX_SAMPLES}"))),
|
||||
None => Ok((m.steps as usize).saturating_add(1).clamp(min, MAX_SAMPLES)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The study step sample `k` of `n` is at.
|
||||
fn step_of(m: &MotionStudy, k: usize, n: usize) -> f64 {
|
||||
f64::from(m.steps) * k as f64 / n.saturating_sub(1).max(1) as f64
|
||||
}
|
||||
|
||||
/// Plays study `m` on a copy of the design in `n` samples, each driven from the one before (so
|
||||
/// closed loops follow on their branch, as `motion.play` places them; contact sets stop it only
|
||||
/// when `contact`). `each` sees the copy at every sample and answers whether to go on. Returns
|
||||
/// where the motion stopped short (all null when it did not).
|
||||
fn play(s: &Session, m: &MotionStudy, n: usize, contact: bool, mut each: impl FnMut(&Session, usize) -> Result<bool>) -> Result<Value> {
|
||||
let mut t = s.scratch();
|
||||
// Played from where the parts are placed: moves only shown are not where joints are solved.
|
||||
t.pending_moves.clear();
|
||||
if !contact {
|
||||
t.doc_mut().assembly.contact_enabled = false;
|
||||
}
|
||||
let given = keyed(m);
|
||||
for k in 0..n {
|
||||
let want = values_at(&t, m, step_of(m, k, n));
|
||||
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
|
||||
let go = each(&t, k)?;
|
||||
if r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object() {
|
||||
return Ok(json!({"stopped_at": k, "stopped_by_loop": r["stopped_by_loop"], "stopped_by_contact": r["stopped_by_contact"]}));
|
||||
}
|
||||
if !go {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(json!({"stopped_at": null, "stopped_by_loop": null, "stopped_by_contact": null}))
|
||||
}
|
||||
|
||||
/// The derivative of samples `v` spaced `h` apart: central differences inside, second-order
|
||||
/// one-sided at the ends (a plain difference with two samples, 0 with one).
|
||||
fn derivative(v: &[f64], h: f64) -> Vec<f64> {
|
||||
let n = v.len();
|
||||
let at = |i: usize| v.get(i).copied().unwrap_or(0.0);
|
||||
(0..n)
|
||||
.map(|k| match n {
|
||||
0 | 1 => 0.0,
|
||||
2 => (at(1) - at(0)) / h,
|
||||
_ if k == 0 => (-3.0 * at(0) + 4.0 * at(1) - at(2)) / (2.0 * h),
|
||||
_ if k + 1 == n => (3.0 * at(k) - 4.0 * at(k - 1) + at(k - 2)) / (2.0 * h),
|
||||
_ => (at(k + 1) - at(k - 1)) / (2.0 * h),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The second derivative of samples `v` spaced `h` apart: central differences inside,
|
||||
/// second-order one-sided at the ends (the one difference there is with three samples, 0 with
|
||||
/// fewer).
|
||||
fn second_derivative(v: &[f64], h: f64) -> Vec<f64> {
|
||||
let n = v.len();
|
||||
let at = |i: usize| v.get(i).copied().unwrap_or(0.0);
|
||||
let h2 = h * h;
|
||||
(0..n)
|
||||
.map(|k| match n {
|
||||
0..=2 => 0.0,
|
||||
3 => (at(0) - 2.0 * at(1) + at(2)) / h2,
|
||||
_ if k == 0 => (2.0 * at(0) - 5.0 * at(1) + 4.0 * at(2) - at(3)) / h2,
|
||||
_ if k + 1 == n => (2.0 * at(k) - 5.0 * at(k - 1) + 4.0 * at(k - 2) - at(k - 3)) / h2,
|
||||
_ => (at(k + 1) - 2.0 * at(k) + at(k - 1)) / h2,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Angles in degrees made continuous: a jump of more than half a turn between samples is taken
|
||||
/// as the angle going round (half a turn exactly is a real step).
|
||||
fn unwrap_degrees(v: &mut [f64]) {
|
||||
let (mut turns, mut prev) = (0.0, None::<f64>);
|
||||
for x in v.iter_mut() {
|
||||
let raw = *x;
|
||||
if let Some(p) = prev
|
||||
&& (raw - p).abs() > 180.0
|
||||
{
|
||||
turns -= 360.0 * ((raw - p) / 360.0).round();
|
||||
}
|
||||
prev = Some(raw);
|
||||
*x = raw + turns;
|
||||
}
|
||||
}
|
||||
|
||||
/// The joint values a plot follows: (joint id, value index).
|
||||
fn plotted(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(u64, usize)>> {
|
||||
let joints = &s.doc.assembly.joints;
|
||||
let ids: Vec<u64> = match p.get("joints") {
|
||||
None | Some(Value::Null) => joints.iter().filter(|j| !j.suppressed).map(|j| j.id).collect(),
|
||||
Some(Value::Array(list)) if list.len() <= MAX_SERIES => list.iter().map(|v| joint_id(s, Some(v), cmd)).collect::<Result<_>>()?,
|
||||
Some(_) => return Err(bad(cmd, format!("`joints` must list at most {MAX_SERIES} joints"))),
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
let dofs = joints.iter().find(|j| j.id == id).map_or(0, |j| j.kind.dofs().len());
|
||||
for i in 0..dofs {
|
||||
if !out.contains(&(id, i)) {
|
||||
out.push((id, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() > MAX_SERIES {
|
||||
return Err(bad(cmd, format!("more than {MAX_SERIES} joint values: list the `joints` to plot")));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) fn plot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "motion.plot";
|
||||
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
|
||||
let n = samples(p, &m, 3, cmd)?;
|
||||
let duration = match p.get("duration") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
// At least a millisecond: shorter sample spacings square to nothing.
|
||||
Some(v.as_f64().filter(|d| (1e-3..=1e9).contains(d)).ok_or_else(|| bad(cmd, "`duration` must be seconds, 0.001 or more"))?)
|
||||
}
|
||||
};
|
||||
let series = plotted(s, p, cmd)?;
|
||||
let given = keyed(&m);
|
||||
let point = if p.get("point").is_some() || p.get("occurrence").is_some() { Some(traced_point(s, p, cmd)?) } else { None };
|
||||
let mut values: Vec<Vec<f64>> = vec![Vec::new(); series.len()];
|
||||
let mut path: Vec<Vec3> = Vec::new();
|
||||
let mut taken = 0;
|
||||
let stop = play(s, &m, n, true, |t, _| {
|
||||
taken += 1;
|
||||
let now = joints::joint_values(&t.doc.assembly);
|
||||
for ((id, i), out) in series.iter().zip(values.iter_mut()) {
|
||||
out.push(now.get(id).and_then(|q| q.get(*i)).copied().unwrap_or(0.0));
|
||||
}
|
||||
if let Some((occ, local)) = &point {
|
||||
path.push(apply_point(&path_world(t, occ, cmd)?, *local));
|
||||
}
|
||||
Ok(true)
|
||||
})?;
|
||||
// Sample spacing in steps, or in seconds when the study has a duration.
|
||||
let seconds_per_step = duration.map(|d| d / f64::from(m.steps));
|
||||
let h = f64::from(m.steps) / (n - 1) as f64 * seconds_per_step.unwrap_or(1.0);
|
||||
let per = if duration.is_some() { "s" } else { "step" };
|
||||
let steps: Vec<f64> = (0..taken).map(|k| step_of(&m, k, n)).collect();
|
||||
let mut out = json!({"study": m.name, "steps": m.steps, "samples": taken, "step": steps});
|
||||
if let Some(sps) = seconds_per_step {
|
||||
out["time"] = steps.iter().map(|st| st * sps).collect();
|
||||
}
|
||||
let joints_out: Vec<Value> = series
|
||||
.iter()
|
||||
.zip(values.iter_mut())
|
||||
.map(|((id, i), v)| {
|
||||
let j = s.doc.assembly.joints.iter().find(|j| j.id == *id);
|
||||
let angle = j.is_some_and(|j| j.kind.is_angle(*i));
|
||||
let unit = if angle { "deg" } else { "mm" };
|
||||
if angle {
|
||||
v.iter_mut().for_each(|x| *x = x.to_degrees());
|
||||
// Keyed values are as the study sets them, and values beyond half a turn
|
||||
// (through motion links) already run on; a loop can hand back a follower's
|
||||
// angle within half a turn, a turn round.
|
||||
if !given.contains(&(*id, *i)) && v.iter().all(|x| x.abs() <= 180.0 + 1e-9) {
|
||||
unwrap_degrees(v);
|
||||
}
|
||||
}
|
||||
json!({"joint": id, "name": j.map(|j| j.name.clone()), "index": i, "dof": j.and_then(|j| j.kind.dofs().get(*i).copied()),
|
||||
"unit": unit, "velocity_unit": format!("{unit}/{per}"), "acceleration_unit": format!("{unit}/{per}²"),
|
||||
"value": v, "velocity": derivative(v, h), "acceleration": second_derivative(v, h)})
|
||||
})
|
||||
.collect();
|
||||
out["joints"] = json!(joints_out);
|
||||
if let Some((occ, _)) = &point {
|
||||
let axis = |c: usize| -> Vec<f64> { path.iter().map(|q| [q.x, q.y, q.z].get(c).copied().unwrap_or(0.0)).collect() };
|
||||
let d: Vec<(Vec<f64>, Vec<f64>)> = (0..3).map(|c| (derivative(&axis(c), h), second_derivative(&axis(c), h))).collect();
|
||||
let vec_at = |k: usize, second: bool| -> Vec3 {
|
||||
let c = |i: usize| d.get(i).and_then(|(v, a)| if second { a.get(k) } else { v.get(k) }).copied().unwrap_or(0.0);
|
||||
Vec3::new(c(0), c(1), c(2))
|
||||
};
|
||||
let (vel, acc): (Vec<Vec3>, Vec<Vec3>) = (0..path.len()).map(|k| (vec_at(k, false), vec_at(k, true))).unzip();
|
||||
let xyz = |list: &[Vec3]| -> Value { list.iter().map(|v| json!([v.x, v.y, v.z])).collect() };
|
||||
let name = s.doc.occurrences.iter().find(|o| Some(&o.id) == occ.last()).map_or_else(|| "root".to_string(), |o| o.name.clone());
|
||||
out["point"] = json!({"occurrence": name, "unit": "mm", "velocity_unit": format!("mm/{per}"), "acceleration_unit": format!("mm/{per}²"),
|
||||
"position": xyz(&path), "velocity": xyz(&vel), "acceleration": xyz(&acc),
|
||||
"speed": vel.iter().map(|v| v.len()).collect::<Vec<_>>(), "acceleration_norm": acc.iter().map(|v| v.len()).collect::<Vec<_>>()});
|
||||
}
|
||||
for k in ["stopped_at", "stopped_by_loop", "stopped_by_contact"] {
|
||||
out[k] = stop[k].clone();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One pair of parts that collides along a study.
|
||||
struct Collision {
|
||||
names: (String, String),
|
||||
/// The samples where they overlap, in order.
|
||||
samples: Vec<usize>,
|
||||
depth: f64,
|
||||
deepest: usize,
|
||||
/// The design at the deepest sample (its placements).
|
||||
at_deepest: Arc<Document>,
|
||||
}
|
||||
|
||||
/// 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<f64> {
|
||||
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();
|
||||
for (comp, path, m) in doc.placements() {
|
||||
// A body belongs to the innermost of the two on its path, as contact sets pair them.
|
||||
let side = match path.iter().rev().find(|o| **o == a || **o == b) {
|
||||
Some(o) if *o == a => 0,
|
||||
Some(_) => 1,
|
||||
None => continue,
|
||||
};
|
||||
for body in st.bodies.iter().filter(|x| doc.model_body_component(x) == comp && !x.body.is_mesh()) {
|
||||
let frame = doc.model_body_offset(body).map(|o| mat_mul(&m, o)).unwrap_or(m);
|
||||
let local = body.mesh().bounds();
|
||||
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 };
|
||||
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));
|
||||
}
|
||||
}
|
||||
let mut total = 0.0;
|
||||
for (fa, xa, ba) in sides.first()? {
|
||||
for (fb, xb, bb) in sides.get(1)? {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(total)
|
||||
}
|
||||
|
||||
/// Contiguous runs of samples, as study step ranges.
|
||||
fn ranges(m: &MotionStudy, samples: &[usize], n: usize) -> Vec<[f64; 2]> {
|
||||
let mut out: Vec<(usize, usize)> = Vec::new();
|
||||
for &k in samples {
|
||||
match out.last_mut() {
|
||||
Some(run) if run.1 + 1 == k => run.1 = k,
|
||||
_ => out.push((k, k)),
|
||||
}
|
||||
}
|
||||
out.into_iter().map(|(a, b)| [step_of(m, a, n), step_of(m, b, n)]).collect()
|
||||
}
|
||||
|
||||
pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "motion.interference";
|
||||
let m = s.doc.assembly.studies.get(study_index(s, p, cmd)?).cloned().ok_or_else(|| bad(cmd, "study"))?;
|
||||
let n = samples(p, &m, 2, cmd)?;
|
||||
let everything = || vec![s.doc.occurrences.iter().map(|o| o.id).collect::<Vec<u64>>()];
|
||||
// Each of `occurrences` only against these.
|
||||
let against = match p.get("against") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) if p.get("occurrences").is_none() => return Err(bad(cmd, "`against` checks the `occurrences` against other parts: list them too")),
|
||||
Some(v) => Some(occurrences(s, &json!({"occurrences": v}), cmd)?),
|
||||
};
|
||||
let sets: Vec<Vec<u64>> = match (p.get("occurrences"), bool_(p, "contact_sets").unwrap_or(false)) {
|
||||
(Some(_), true) => return Err(bad(cmd, "give `occurrences` or `contact_sets`, not both")),
|
||||
(Some(_), false) => {
|
||||
let mut list = occurrences(s, p, cmd)?;
|
||||
if list.len() + against.as_ref().map_or(0, Vec::len) < 2 {
|
||||
return Err(bad(cmd, "list two or more occurrences to check against each other"));
|
||||
}
|
||||
for o in against.iter().flatten() {
|
||||
if !list.contains(o) {
|
||||
list.push(*o);
|
||||
}
|
||||
}
|
||||
vec![list]
|
||||
}
|
||||
(None, true) => {
|
||||
let a = &s.doc.assembly;
|
||||
let sets: Vec<Vec<u64>> =
|
||||
if a.contact_all { everything() } else { a.contact_sets.iter().filter(|c| !c.suppressed).map(|c| c.occurrences.clone()).collect() };
|
||||
if sets.is_empty() {
|
||||
return Err(bad(cmd, "the design has no contact sets"));
|
||||
}
|
||||
sets
|
||||
}
|
||||
(None, false) => everything(),
|
||||
};
|
||||
let mut geometry = ContactGeometry::of_sets(s, &sets).map_err(|e| match e {
|
||||
EngineError::BadParams { msg, .. } => bad(cmd, format!("{msg} (check fewer parts: list the `occurrences`)")),
|
||||
e => e,
|
||||
})?;
|
||||
if let Some(b) = &against {
|
||||
let a = occurrences(s, p, cmd)?;
|
||||
geometry.keep_pairs(|x, y| (a.contains(&x) && b.contains(&y)) || (a.contains(&y) && b.contains(&x)));
|
||||
}
|
||||
let mut found: BTreeMap<(u64, u64), Collision> = BTreeMap::new();
|
||||
let (mut work, mut checked, mut truncated) = (0usize, 0usize, false);
|
||||
let stop = play(s, &m, n, false, |t, k| {
|
||||
// Placing the meshes is work too, also where nothing comes near.
|
||||
work = work.saturating_add(geometry.vertex_count());
|
||||
if work > MAX_WORK {
|
||||
truncated = true;
|
||||
return Ok(false);
|
||||
}
|
||||
let hits: Vec<(Member, Member, f64)> = match geometry.hits(t, &mut work, MAX_WORK, true) {
|
||||
Ok(h) => h,
|
||||
Err(_) if work > MAX_WORK => {
|
||||
truncated = true;
|
||||
return Ok(false);
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
checked = k + 1;
|
||||
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)) };
|
||||
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(),
|
||||
});
|
||||
if c.samples.last() != Some(&k) {
|
||||
c.samples.push(k);
|
||||
}
|
||||
if depth > c.depth {
|
||||
(c.depth, c.deepest, c.at_deepest) = (depth, k, t.doc.clone());
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
})?;
|
||||
// Nothing checked is not clear.
|
||||
if truncated && checked == 0 {
|
||||
return Err(bad(cmd, "the check ran out of its work budget before its first step: check fewer parts (occurrences, against)"));
|
||||
}
|
||||
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<Value> = 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 };
|
||||
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})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({"study": m.name, "steps": m.steps, "clear": collisions.is_empty(), "collisions": collisions,
|
||||
"pairs": geometry.pair_count(), "samples": checked, "truncated": truncated});
|
||||
if truncated {
|
||||
out["checked_to"] = json!(checked.checked_sub(1).map(|k| step_of(&m, k, n)));
|
||||
}
|
||||
out["stopped_at"] = stop["stopped_at"].clone();
|
||||
out["stopped_by_loop"] = stop["stopped_by_loop"].clone();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The differences are exact for a quadratic: its velocity and acceleration everywhere,
|
||||
/// the ends too.
|
||||
#[test]
|
||||
fn finite_differences_follow_a_polynomial() {
|
||||
let h = 0.5;
|
||||
let f = |x: f64| 2.0 * x * x - 3.0 * x + 1.0;
|
||||
let v: Vec<f64> = (0..7).map(|k| f(k as f64 * h)).collect();
|
||||
let d = derivative(&v, h);
|
||||
let a = second_derivative(&v, h);
|
||||
for (k, (dk, ak)) in d.iter().zip(&a).enumerate() {
|
||||
let x = k as f64 * h;
|
||||
assert!((dk - (4.0 * x - 3.0)).abs() < 1e-9, "{k}: {dk}");
|
||||
assert!((ak - 4.0).abs() < 1e-9, "{k}: {ak}");
|
||||
}
|
||||
assert_eq!(derivative(&[1.0, 3.0], 2.0), vec![1.0, 1.0]);
|
||||
assert_eq!(second_derivative(&[1.0, 3.0], 2.0), vec![0.0, 0.0]);
|
||||
assert_eq!(derivative(&[5.0], 1.0), vec![0.0]);
|
||||
assert!(derivative(&[], 1.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn angles_unwrap_across_half_turns() {
|
||||
let mut v = vec![170.0, 179.0, -172.0, -160.0, 175.0];
|
||||
unwrap_degrees(&mut v);
|
||||
assert_eq!(v, vec![170.0, 179.0, 188.0, 200.0, 175.0]);
|
||||
// Half a turn a sample is a step, not a wrap.
|
||||
let mut v = vec![0.0, 180.0, 360.0];
|
||||
unwrap_degrees(&mut v);
|
||||
assert_eq!(v, vec![0.0, 180.0, 360.0]);
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
//! `motion.plot` against the analytic motion of a four-bar and a slider-crank, and
|
||||
//! `motion.interference` on two blocks pushed through each other at a known step.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use super::{four_bar, occ, part, pin, rocker_pin, run, slider_crank};
|
||||
use crate::Session;
|
||||
|
||||
/// A joint's series in a plot, by joint name.
|
||||
fn series<'a>(r: &'a Value, name: &str) -> &'a Value {
|
||||
r["joints"].as_array().and_then(|list| list.iter().find(|j| j["name"] == name)).unwrap_or(&Value::Null)
|
||||
}
|
||||
|
||||
fn nums(v: &Value) -> Vec<f64> {
|
||||
v.as_array().into_iter().flatten().map(|x| x.as_f64().unwrap_or(f64::NAN)).collect()
|
||||
}
|
||||
|
||||
/// The crank turns at a constant 50°/s (a full turn in 7.2 s). The rocker turns at
|
||||
/// ω4 = ω2·a·sin(θ2 − θ3) / (c·sin(θ4 − θ3)) (crank a = 20, rocker c = 40; θ2, θ3 and θ4 the
|
||||
/// crank, coupler and rocker angles), from differentiating the loop a·e^iθ2 + b·e^iθ3 = d + c·e^iθ4.
|
||||
#[test]
|
||||
fn four_bar_rocker_velocity_matches_its_analytic_derivative() {
|
||||
let (mut s, _, q0) = four_bar();
|
||||
run(&mut s, "motion.study", json!({"name": "Turn", "steps": 360, "keys": [{"joint": "Crank", "points": [[0, 0], [360, 360]]}]}));
|
||||
let before = s.doc.clone();
|
||||
let r = run(&mut s, "motion.plot", json!({"study": "Turn", "joints": ["Crank", "Rocker"], "samples": 181, "duration": 7.2}));
|
||||
assert_eq!(*s.doc, *before, "a plot leaves the design as it was");
|
||||
assert!(r["stopped_at"].is_null() && r["samples"] == 181, "{}", r["stopped_by_loop"]);
|
||||
assert_eq!(r["joints"].as_array().map(Vec::len), Some(2));
|
||||
let (crank, rocker) = (series(&r, "Crank"), series(&r, "Rocker"));
|
||||
assert_eq!((rocker["unit"].as_str(), rocker["velocity_unit"].as_str()), (Some("deg"), Some("deg/s")));
|
||||
let time = nums(&r["time"]);
|
||||
assert!((time.last().copied().unwrap_or(0.0) - 7.2).abs() < 1e-9 && (time[1] - 0.04).abs() < 1e-12, "{time:?}");
|
||||
// The crank: exactly as keyed, at a constant speed.
|
||||
for ((v, w), a) in nums(&crank["value"]).iter().zip(nums(&crank["velocity"])).zip(nums(&crank["acceleration"])) {
|
||||
assert!((w - 50.0).abs() < 1e-6 && a.abs() < 1e-6, "{v}°: {w} deg/s, {a} deg/s²");
|
||||
}
|
||||
let (value, velocity) = (nums(&rocker["value"]), nums(&rocker["velocity"]));
|
||||
let start = q0.y.atan2(q0.x - 45.0);
|
||||
let (mut q, mut peak, mut worst) = (q0, 0.0f64, 0.0f64);
|
||||
for k in 0..181 {
|
||||
let v = 2.0 * k as f64;
|
||||
if k > 0 {
|
||||
q = rocker_pin(v - 2.0, v, q);
|
||||
}
|
||||
let th2 = (90.0 + v).to_radians();
|
||||
let p = Vec3::new(20.0 * th2.cos(), 20.0 * th2.sin(), 0.0);
|
||||
let (th3, th4) = ((q - p).y.atan2((q - p).x), q.y.atan2(q.x - 45.0));
|
||||
// The rocker's value is its turn from where it was assembled, made continuous.
|
||||
let turned = (th4 - start).to_degrees();
|
||||
assert!(((value[k] - turned + 540.0).rem_euclid(360.0) - 180.0).abs() < 1e-6, "{v}°: {} wants {turned}", value[k]);
|
||||
let w4 = 50.0 * 20.0 * (th2 - th3).sin() / (40.0 * (th4 - th3).sin());
|
||||
peak = peak.max(w4.abs());
|
||||
worst = worst.max((velocity[k] - w4).abs());
|
||||
}
|
||||
// Central differences 0.04 s apart: within 0.2 % of the fastest swing.
|
||||
assert!(peak > 40.0 && worst < 2e-3 * peak, "worst {worst} deg/s of {peak} deg/s");
|
||||
}
|
||||
|
||||
/// The piston of a slider-crank (crank a = 15, rod b = 40) turning at 100°/s sits at
|
||||
/// x = a·cos θ + S with S = √(b² − a²·sin²θ), so it accelerates at
|
||||
/// ω²·(−a·cos θ − a²·cos 2θ / S − a⁴·sin²θ·cos²θ / S³).
|
||||
#[test]
|
||||
fn slider_crank_piston_acceleration_matches_its_analytic_form() {
|
||||
let (mut s, _, s0) = slider_crank();
|
||||
run(&mut s, "motion.study", json!({"name": "Turn", "steps": 360, "keys": [{"joint": "Crank", "points": [[0, 0], [360, 360]]}]}));
|
||||
let p = json!({"study": "Turn", "joints": ["Bore"], "occurrence": "Piston", "point": [s0.x, s0.y, s0.z], "samples": 181, "duration": 3.6});
|
||||
let r = run(&mut s, "motion.plot", p);
|
||||
assert!(r["stopped_at"].is_null() && r["samples"] == 181, "{}", r["stopped_by_loop"]);
|
||||
let point = &r["point"];
|
||||
assert_eq!((point["occurrence"].as_str(), point["acceleration_unit"].as_str()), (Some("Piston:1"), Some("mm/s²")));
|
||||
let at = |key: &str, k: usize, c: usize| point[key][k][c].as_f64().unwrap_or(f64::NAN);
|
||||
let (a, b, w) = (15.0f64, 40.0f64, 100.0f64.to_radians());
|
||||
let (mut peak, mut worst) = (0.0f64, 0.0f64);
|
||||
for k in 0..181 {
|
||||
let th = (90.0 + 2.0 * k as f64).to_radians();
|
||||
let root = (b * b - (a * th.sin()).powi(2)).sqrt();
|
||||
assert!((at("position", k, 0) - (a * th.cos() + root)).abs() < 1e-6, "{k}");
|
||||
let want = w * w * (-a * th.cos() - a * a * (2.0 * th).cos() / root - a.powi(4) * (th.sin() * th.cos()).powi(2) / root.powi(3));
|
||||
peak = peak.max(want.abs());
|
||||
// The ends take one-sided differences; inside, central ones.
|
||||
let tolerance = if k == 0 || k == 180 { 2e-2 } else { 2e-3 };
|
||||
worst = worst.max((at("acceleration", k, 0) - want).abs() / tolerance);
|
||||
assert!(at("acceleration", k, 1).abs() < 1e-6 && at("acceleration", k, 2).abs() < 1e-6, "it stays on its axis");
|
||||
}
|
||||
assert!(peak > 40.0 && worst < peak, "worst {worst} of {peak} mm/s² (scaled by tolerance)");
|
||||
// The bore's value is the piston's travel, so its acceleration is the piston's along x.
|
||||
let bore = series(&r, "Bore");
|
||||
assert_eq!(bore["acceleration_unit"], "mm/s²");
|
||||
let along = |k: usize| nums(&bore["value"])[k] - nums(&bore["value"])[0];
|
||||
let sign = if along(90) * (at("position", 90, 0) - at("position", 0, 0)) < 0.0 { -1.0 } else { 1.0 };
|
||||
for (k, acc) in nums(&bore["acceleration"]).iter().enumerate() {
|
||||
assert!((acc - sign * at("acceleration", k, 0)).abs() < 1e-6, "{k}: {acc}");
|
||||
}
|
||||
// Per step without a duration: 2 steps between samples, 1° a step.
|
||||
let r = run(&mut s, "motion.plot", json!({"study": "Turn", "joints": ["Crank"], "samples": 181}));
|
||||
let crank = series(&r, "Crank");
|
||||
assert!(r["time"].is_null() && crank["velocity_unit"] == "deg/step", "{crank}");
|
||||
assert!(nums(&crank["velocity"]).iter().all(|v| (v - 1.0).abs() < 1e-9));
|
||||
}
|
||||
|
||||
/// A dial linked 2:1 to the crank turns on past a turn: its values are not taken a turn round,
|
||||
/// even half a turn a sample.
|
||||
#[test]
|
||||
fn a_linked_value_past_half_a_turn_runs_on() {
|
||||
let (mut s, _, _) = four_bar();
|
||||
part(&mut s, "Dial", [80.0, 0.0, -5.0]);
|
||||
pin(&mut s, "revolute", "Dial", "Ground", "Dial", Vec3::new(80.0, 0.0, 0.0), Vec3::Z);
|
||||
run(&mut s, "joint.motion_link", json!({"a": "Crank", "b": "Dial", "ratio": 2}));
|
||||
run(&mut s, "motion.study", json!({"name": "Turn", "steps": 2, "keys": [{"joint": "Crank", "points": [[0, 0], [2, 360]]}]}));
|
||||
let r = run(&mut s, "motion.plot", json!({"study": "Turn", "joints": ["Dial"], "samples": 3}));
|
||||
let v: Vec<f64> = nums(&series(&r, "Dial")["value"]).iter().map(|x| x.abs()).collect();
|
||||
assert!((v[1] - 360.0).abs() < 1e-6 && (v[2] - 720.0).abs() < 1e-6, "{r}");
|
||||
}
|
||||
|
||||
/// Cubes A (grounded, x 0…10) and B (x 20…30) on a slider along x, B 10 mm away at value 10.
|
||||
fn rail() -> Session {
|
||||
let mut s = Session::default();
|
||||
for (name, x) in [("A", 0), ("B", 20)] {
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
run(&mut s, "component.create", json!({"name": name}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]}));
|
||||
}
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
let a = occ(&s, "A");
|
||||
run(&mut s, "occurrence.ground", json!({"occurrence": a, "grounded": true}));
|
||||
run(&mut s, "joint.create", json!({"type": "slider", "a": {"face": [10, 5, 5]}, "b": {"face": [20, 5, 5]}, "name": "Rail"}));
|
||||
run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 10}));
|
||||
s
|
||||
}
|
||||
|
||||
/// B is pushed 1 mm a step from 10 mm away to 5 mm into A: the faces touch at step 10 and the
|
||||
/// blocks overlap from step 11 to the end, 100 mm³ more each step.
|
||||
#[test]
|
||||
fn interference_names_the_step_two_parts_start_to_collide() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "motion.study", json!({"name": "Push", "steps": 15, "keys": [{"joint": "Rail", "points": [[0, 10], [15, -5]]}]}));
|
||||
// A contact set would stop the motion where the faces touch; the check plays through.
|
||||
run(&mut s, "contact.create", json!({"occurrences": ["A", "B"]}));
|
||||
let before = s.doc.clone();
|
||||
for p in [json!({"study": "Push"}), json!({"study": "Push", "occurrences": ["A", "B"]}), json!({"study": "Push", "contact_sets": true})] {
|
||||
let r = run(&mut s, "motion.interference", p.clone());
|
||||
assert_eq!(*s.doc, *before, "the design is left as it was");
|
||||
assert!(r["clear"] == false && r["samples"] == 16 && r["pairs"] == 1 && r["truncated"] == false, "{p}: {r}");
|
||||
let c = &r["collisions"][0];
|
||||
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}");
|
||||
}
|
||||
// B against a far block C only: B's pass through A is not asked about.
|
||||
run(&mut s, "component.create", json!({"name": "C"}));
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 50, 0]}));
|
||||
run(&mut s, "component.activate", json!({"component": "root"}));
|
||||
let r = run(&mut s, "motion.interference", json!({"study": "Push", "occurrences": ["B"], "against": ["C"]}));
|
||||
assert!(r["clear"] == true && r["pairs"] == 1, "{r}");
|
||||
let r = run(&mut s, "motion.interference", json!({"study": "Push", "occurrences": ["B"], "against": ["A", "C"]}));
|
||||
assert!(r["pairs"] == 2 && r["collisions"].as_array().map(Vec::len) == Some(1) && r["collisions"][0]["first_step"] == 11.0, "{r}");
|
||||
assert!(s.execute("motion.interference", &json!({"study": "Push", "against": ["A"]})).is_err());
|
||||
// Pushed only to touching, they never pass through each other.
|
||||
run(&mut s, "motion.study", json!({"study": "Push", "keys": [{"joint": "Rail", "points": [[0, 10], [15, 0]]}]}));
|
||||
let r = run(&mut s, "motion.interference", json!({"study": "Push"}));
|
||||
assert!(r["clear"] == true && r["collisions"] == json!([]), "{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]
|
||||
fn studies_by_id_or_name() {
|
||||
let mut s = rail();
|
||||
let keys = json!([{"joint": "Rail", "points": [[0, 10], [15, -5]]}]);
|
||||
let first = run(&mut s, "motion.study", json!({"name": "Late", "steps": 15, "keys": keys}))["study"].as_u64().unwrap_or(0);
|
||||
run(&mut s, "motion.study", json!({"name": first.to_string(), "steps": 15, "keys": keys}));
|
||||
assert_eq!(run(&mut s, "motion.plot", json!({"study": first, "samples": 3}))["study"], "Late");
|
||||
assert_eq!(run(&mut s, "motion.plot", json!({"study": first.to_string(), "samples": 3}))["study"], first.to_string());
|
||||
}
|
||||
|
||||
/// Hostile parameters are refused, never a panic.
|
||||
#[test]
|
||||
fn motion_analysis_refuses_what_it_cannot_do() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "motion.study", json!({"name": "Push", "steps": 15, "keys": [{"joint": "Rail", "points": [[0, 10], [15, -5]]}]}));
|
||||
let refused = [
|
||||
("motion.plot", json!({"study": "Nope"})),
|
||||
("motion.plot", json!({"study": "Push", "samples": 2})),
|
||||
("motion.plot", json!({"study": "Push", "samples": 1e9})),
|
||||
("motion.plot", json!({"study": "Push", "samples": "many"})),
|
||||
("motion.plot", json!({"study": "Push", "duration": 0})),
|
||||
("motion.plot", json!({"study": "Push", "duration": -3})),
|
||||
("motion.plot", json!({"study": "Push", "duration": 1e-200})),
|
||||
("motion.plot", json!({"study": "Push", "joints": ["Nope"]})),
|
||||
("motion.plot", json!({"study": "Push", "joints": vec![json!("Rail"); 300]})),
|
||||
("motion.plot", json!({"study": "Push", "point": [1, 2]})),
|
||||
("motion.plot", json!({"study": "Push", "occurrence": "B", "point": [1e300, 0, 0]})),
|
||||
("motion.interference", json!({"study": "Push", "samples": 1})),
|
||||
("motion.interference", json!({"study": "Push", "samples": f64::MAX})),
|
||||
("motion.interference", json!({"study": "Push", "occurrences": ["A"]})),
|
||||
("motion.interference", json!({"study": "Push", "occurrences": ["A", "B"], "contact_sets": true})),
|
||||
("motion.interference", json!({"study": "Push", "contact_sets": true})),
|
||||
];
|
||||
for (cmd, p) in refused {
|
||||
assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}");
|
||||
}
|
||||
// A point of a part that does not move has no velocity.
|
||||
let r = run(&mut s, "motion.plot", json!({"study": "Push", "occurrence": "A", "point": [5, 5, 5]}));
|
||||
assert!(r["point"]["speed"].as_array().is_some_and(|v| v.len() == 16 && v.iter().all(|x| x.as_f64() == Some(0.0))), "{r}");
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
//! Motion animations (`motion.export_animation`): a study played, or one joint driven, drawn
|
||||
//! frame by frame by the headless renderer the host installed ([`crate::capture`]) and written as
|
||||
//! an animated GIF or a folder of PNG frames. Sampled on a copy, as a trace is: the design is not
|
||||
//! changed.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{drive_with_contact, motion_plan, sample_count};
|
||||
use crate::capture::{self, Renderer};
|
||||
use crate::params::{bad, str_};
|
||||
use crate::render::Camera;
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Most frames of one animation.
|
||||
const MAX_FRAMES: usize = 1000;
|
||||
/// Largest frame side, in pixels.
|
||||
const MAX_SIDE: u32 = 4096;
|
||||
/// Most pixels of a GIF's frames together: they are held in memory (4 bytes each) until the
|
||||
/// palette is chosen, so 256 MB at most.
|
||||
const MAX_GIF_PIXELS: usize = 1 << 26;
|
||||
/// Most pixels of a PNG folder's frames together (each frame is written as it is drawn): about
|
||||
/// 500 frames of 1920 × 1080.
|
||||
const MAX_PNG_PIXELS: usize = 1 << 30;
|
||||
/// The camera fields `camera` may set: those of `ui.camera`'s reply.
|
||||
const FIELDS: [&str; 7] = ["target", "yaw", "pitch", "roll", "distance", "fov", "up"];
|
||||
|
||||
pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
export_with(s, p, capture::installed().as_deref())
|
||||
}
|
||||
|
||||
/// [`export`] drawn by `renderer`.
|
||||
pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -> Result<Value> {
|
||||
let cmd = "motion.export_animation";
|
||||
let path = str_(p, "path")
|
||||
.filter(|x| !x.trim().is_empty() && x.len() <= 4096 && !x.chars().any(char::is_control))
|
||||
.ok_or_else(|| bad(cmd, "`path` must name a .gif file, or a folder for PNG frames"))?;
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".png") {
|
||||
return Err(bad(cmd, "`path` is a .gif file or a folder for the PNG frames (frame-0001.png, …), not one .png"));
|
||||
}
|
||||
let gif = lower.ends_with(".gif");
|
||||
// In the browser written files stay in memory until the host takes them, and the host is not
|
||||
// told of removed ones: a folder of frames would pile up there.
|
||||
if !gif && cfg!(target_arch = "wasm32") {
|
||||
return Err(bad(cmd, "a folder of PNG frames is not available in the browser: give a .gif path"));
|
||||
}
|
||||
let side = |key: &str, default: u32| match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.is_finite() && (16.0..=f64::from(MAX_SIDE)).contains(n))
|
||||
.map(|n| n.round() as u32)
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be 16…{MAX_SIDE} pixels"))),
|
||||
};
|
||||
let (width, height) = (side("width", 800)?, side("height", 500)?);
|
||||
let fps = match p.get("fps") {
|
||||
None => 20.0,
|
||||
Some(v) => v.as_f64().filter(|n| n.is_finite() && (1.0..=50.0).contains(n)).ok_or_else(|| bad(cmd, "`fps` must be 1…50"))?,
|
||||
};
|
||||
let cam = camera(s, p.get("camera"), cmd)?;
|
||||
let shown = |key: &str| match p.get(key) {
|
||||
None => Ok(true),
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
|
||||
};
|
||||
let guides = crate::view::Guides { grid: shown("grid")?, axes: shown("axes")? };
|
||||
let (default, given, plan) = motion_plan(s, p, cmd)?;
|
||||
// At least 4 frames fit even at the largest size.
|
||||
let max = MAX_FRAMES.min(if gif { MAX_GIF_PIXELS } else { MAX_PNG_PIXELS } / (width as usize * height as usize));
|
||||
let n = sample_count(p, default.min(max), max, cmd).map_err(|_| bad(cmd, format!("`samples` must be 2…{max} for {width} × {height} frames")))?;
|
||||
let renderer = renderer.ok_or_else(|| bad(cmd, "no renderer is installed to draw pictures in this process"))?;
|
||||
// A destination outside an agent's folders is refused before anything is drawn.
|
||||
let io = |e: std::io::Error| bad(cmd, format!("{path}: {e}"));
|
||||
solidcraft_io::vfs::check(path).map_err(io)?;
|
||||
let frame_path = |k: usize| std::path::Path::new(path).join(format!("frame-{k:04}.png")).to_string_lossy().to_string();
|
||||
if !gif {
|
||||
solidcraft_io::vfs::create_dir_all(path).map_err(io)?;
|
||||
// The frames of an earlier export here go first, so the folder never mixes two
|
||||
// animations: not after a shorter one, nor when this one fails part way.
|
||||
for stale in (1..=MAX_FRAMES).map(frame_path).filter(|f| solidcraft_io::vfs::exists(f)) {
|
||||
solidcraft_io::vfs::remove(&stale).map_err(|e| bad(cmd, format!("{stale}: {e}")))?;
|
||||
}
|
||||
}
|
||||
let mut t = s.scratch();
|
||||
// From where the parts are placed: moves only shown (an exploded view, the pose an open
|
||||
// Motion Study dialog shows) are not where the joints are solved.
|
||||
t.pending_moves.clear();
|
||||
let (mut frames, mut bytes, mut drawn_by) = (Vec::new(), 0, "");
|
||||
let mut stop = (Value::Null, Value::Null, Value::Null);
|
||||
for k in 0..n {
|
||||
let want = plan(&t, k, n);
|
||||
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
|
||||
if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) {
|
||||
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
|
||||
}
|
||||
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 {
|
||||
frames.push(picture.rgba);
|
||||
} else {
|
||||
let png = crate::render::png(width as usize, height as usize, picture.rgba).ok_or_else(|| bad(cmd, "PNG encoding failed"))?;
|
||||
let file = frame_path(k + 1);
|
||||
solidcraft_io::vfs::write(&file, &png).map_err(|e| bad(cmd, format!("{file}: {e}")))?;
|
||||
bytes += png.len();
|
||||
}
|
||||
}
|
||||
let mut out = json!({"path": path, "format": if gif { "gif" } else { "png" }, "frames": n, "width": width, "height": height});
|
||||
if gif {
|
||||
// GIF counts in hundredths of a second, and viewers slow anything under 2 down.
|
||||
let delay = (100.0 / fps).round().clamp(2.0, 100.0) as u16;
|
||||
let gif = crate::render::gif(width as usize, height as usize, &frames, delay).ok_or_else(|| bad(cmd, "GIF encoding failed"))?;
|
||||
solidcraft_io::write_atomic(std::path::Path::new(path), &gif, false).map_err(io)?;
|
||||
bytes = gif.len();
|
||||
out["fps"] = json!(100.0 / f64::from(delay));
|
||||
}
|
||||
out["bytes"] = json!(bytes);
|
||||
out["renderer"] = json!(drawn_by);
|
||||
if let Some(w) = capture::warning(drawn_by) {
|
||||
out["warning"] = json!(w);
|
||||
}
|
||||
out["stopped_at"] = stop.0;
|
||||
out["stopped_by_loop"] = stop.1;
|
||||
out["stopped_by_contact"] = stop.2;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The camera the frames are drawn from: the session's (`view.apply`), or the home view framing
|
||||
/// the model, with the fields `given` sets (`ui.camera`'s reply sets them all).
|
||||
fn camera(s: &Session, given: Option<&Value>, cmd: &str) -> Result<Camera> {
|
||||
let base = s.camera.unwrap_or_else(|| crate::view::home_camera(s));
|
||||
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()))?;
|
||||
for (k, x) in fields {
|
||||
if !FIELDS.contains(&k.as_str()) {
|
||||
return Err(bad(cmd, format!("unknown camera field `{k}` (it takes {})", FIELDS.join(", "))));
|
||||
}
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert(k.clone(), x.clone());
|
||||
}
|
||||
}
|
||||
let mut cam: Camera = serde_json::from_value(v).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;
|
||||
if !cam.is_valid() || cam.distance > 1e15 || cam.pitch.abs() > std::f64::consts::FRAC_PI_2 || !(0.0..3.0).contains(&cam.fov) {
|
||||
return Err(bad(
|
||||
cmd,
|
||||
"the camera must be finite, with a distance up to 1e15 mm, a pitch within ±π/2 and a fov of 0 (orthographic) to 3 radians",
|
||||
));
|
||||
}
|
||||
// Straight up or down keeps a heading, as ui.camera does.
|
||||
let lim = std::f64::consts::FRAC_PI_2 - 1e-6;
|
||||
cam.pitch = cam.pitch.clamp(-lim, lim);
|
||||
Ok(cam)
|
||||
}
|
||||
@@ -173,235 +173,3 @@ fn exploded_views_show_without_changing_the_design() {
|
||||
);
|
||||
assert_eq!(run(&mut s, "explode.list", json!({}))["views"].as_array().map(Vec::len), Some(2));
|
||||
}
|
||||
|
||||
/// 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<crate::capture::Picture, String> {
|
||||
Ok(crate::capture::Picture { rgba: crate::render::render(scene, cam, w as usize, h as usize).rgba, renderer: "cpu" })
|
||||
}
|
||||
|
||||
/// A folder of its own for one test's files.
|
||||
fn out_dir(test: &str) -> std::path::PathBuf {
|
||||
let dir = solidcraft_io::vfs::temp_dir().join(format!("solidcraft-anim-{test}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A GIF's logical screen size and the number of its frames (image descriptors).
|
||||
fn gif_frames(gif: &[u8]) -> (usize, usize, usize) {
|
||||
let u16_at = |i: usize| usize::from(u16::from_le_bytes([gif[i], gif[i + 1]]));
|
||||
assert_eq!(&gif[..6], b"GIF89a");
|
||||
let mut at = 13 + if gif[10] & 0x80 != 0 { 3 << ((gif[10] & 7) + 1) } else { 0 };
|
||||
let mut frames = 0;
|
||||
// Each block: a size byte and that many bytes, up to a 0.
|
||||
let skip_blocks = |mut at: usize| {
|
||||
while gif[at] != 0 {
|
||||
at += usize::from(gif[at]) + 1;
|
||||
}
|
||||
at + 1
|
||||
};
|
||||
loop {
|
||||
match gif[at] {
|
||||
0x3B => return (u16_at(6), u16_at(8), frames),
|
||||
0x21 => at = skip_blocks(at + 2),
|
||||
0x2C => {
|
||||
frames += 1;
|
||||
at = skip_blocks(at + 11);
|
||||
}
|
||||
b => panic!("unexpected GIF block {b:#x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PNG's width and height (its IHDR).
|
||||
fn png_size(png: &[u8]) -> (u32, u32) {
|
||||
let be = |i: usize| u32::from_be_bytes([png[i], png[i + 1], png[i + 2], png[i + 3]]);
|
||||
(be(16), be(20))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_animation_has_the_frames_and_the_size_asked_for() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]}));
|
||||
let dir = out_dir("size");
|
||||
let before = s.doc.clone();
|
||||
let gif = dir.join("push.gif");
|
||||
let p = json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 6, "width": 64, "height": 40, "fps": 25});
|
||||
let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
assert_eq!(
|
||||
(r["format"].as_str(), r["frames"].as_u64(), r["width"].as_u64(), r["height"].as_u64()),
|
||||
(Some("gif"), Some(6), Some(64), Some(40)),
|
||||
"{r}"
|
||||
);
|
||||
assert_eq!(r["fps"], 25.0, "{r}");
|
||||
let bytes = std::fs::read(&gif).unwrap();
|
||||
assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64));
|
||||
assert_eq!(gif_frames(&bytes), (64, 40, 6));
|
||||
// Without samples: the study's steps + 1.
|
||||
let r =
|
||||
super::animation::export_with(&s, &json!({"study": "Push", "path": gif.to_string_lossy(), "width": 32, "height": 32}), Some(&cpu)).unwrap();
|
||||
assert_eq!(gif_frames(&std::fs::read(&gif).unwrap()), (32, 32, 11), "{r}");
|
||||
// A folder of PNG frames, made where missing; a joint driven instead of a study.
|
||||
let frames = dir.join("frames").join("rail");
|
||||
let p = json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 3, "width": 48, "height": 30});
|
||||
let r = super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["frames"].as_u64()), (Some("png"), Some(3)), "{r}");
|
||||
let mut names: Vec<String> = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["frame-0001.png", "frame-0002.png", "frame-0003.png"]);
|
||||
assert!(names.iter().all(|n| png_size(&std::fs::read(frames.join(n)).unwrap()) == (48, 30)));
|
||||
// A shorter export into the same folder leaves no frames of a longer one behind, past a gap
|
||||
// too; other files stay.
|
||||
std::fs::write(frames.join("notes.txt"), "mine").unwrap();
|
||||
std::fs::write(frames.join("frame-0005.png"), "older").unwrap();
|
||||
super::animation::export_with(&s, &json!({"joint": "Rail", "from": 10, "to": 0, "path": frames.to_string_lossy(), "samples": 2}), Some(&cpu))
|
||||
.unwrap();
|
||||
let mut names: Vec<String> = std::fs::read_dir(&frames).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
|
||||
names.sort();
|
||||
assert_eq!(names, ["frame-0001.png", "frame-0002.png", "notes.txt"]);
|
||||
assert_eq!(*s.doc, *before, "the design is not changed");
|
||||
// Through the registry, with the renderer the host installed.
|
||||
crate::capture::install_test_renderer();
|
||||
let r = run(&mut s, "motion.export_animation", json!({"study": "Push", "path": gif.to_string_lossy(), "samples": 2, "width": 16, "height": 16}));
|
||||
assert_eq!(r["frames"], 2, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_two_frame_drive_gives_two_different_frames() {
|
||||
let s = rail();
|
||||
let dir = out_dir("two");
|
||||
let frames = |name: &str, to: f64| {
|
||||
let folder = dir.join(name);
|
||||
let p = json!({"joint": "Rail", "from": 10, "to": to, "path": folder.to_string_lossy(), "samples": 2, "width": 120, "height": 80});
|
||||
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
(std::fs::read(folder.join("frame-0001.png")).unwrap(), std::fs::read(folder.join("frame-0002.png")).unwrap())
|
||||
};
|
||||
let (a, b) = frames("moved", -5.0);
|
||||
assert_ne!(a, b, "B moved 15 mm between the frames");
|
||||
// Held still, the two frames are the same picture: the difference is the motion.
|
||||
let (c, d) = frames("still", 10.0);
|
||||
assert_eq!(c, d);
|
||||
assert_eq!(a, c, "both start at 10 mm");
|
||||
// Without the ground grid and the axes, the same pose is another picture.
|
||||
let bare = dir.join("bare");
|
||||
let p = json!({"joint": "Rail", "from": 10, "to": 10, "path": bare.to_string_lossy(), "samples": 2, "width": 120, "height": 80, "grid": false, "axes": false});
|
||||
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
assert_ne!(std::fs::read(bare.join("frame-0001.png")).unwrap(), c);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_animation_is_drawn_from_the_camera_given() {
|
||||
let mut s = rail();
|
||||
let dir = out_dir("camera");
|
||||
// A renderer is 'static (hosts install it for the process): it shares what it saw.
|
||||
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let record = {
|
||||
let seen = seen.clone();
|
||||
move |scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32| {
|
||||
seen.lock().unwrap().push(*cam);
|
||||
cpu(scene, cam, w, h)
|
||||
}
|
||||
};
|
||||
let path = dir.join("cam.gif");
|
||||
let base = json!({"joint": "Rail", "from": 10, "to": 0, "path": path.to_string_lossy(), "samples": 3, "width": 40, "height": 30});
|
||||
let with = |camera: Value| {
|
||||
let mut p = base.clone();
|
||||
p["camera"] = camera;
|
||||
p
|
||||
};
|
||||
// ui.camera's reply, every field.
|
||||
let reply = json!({"target": [1.0, 2.0, 3.0], "yaw": 0.5, "pitch": -0.25, "roll": 0.1, "distance": 300.0, "fov": 0.6, "up": "y"});
|
||||
super::animation::export_with(&s, &with(reply.clone()), Some(&record)).unwrap();
|
||||
let cams = std::mem::take(&mut *seen.lock().unwrap());
|
||||
assert_eq!(cams.len(), 3);
|
||||
assert!(cams.iter().all(|c| json!(c) == reply), "{cams:?}");
|
||||
// Fields left out keep the default view: view.apply's camera.
|
||||
run(&mut s, "view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80}}));
|
||||
super::animation::export_with(&s, &with(json!({"yaw": 2.0})), Some(&record)).unwrap();
|
||||
let cams = std::mem::take(&mut *seen.lock().unwrap());
|
||||
assert!(cams.iter().all(|c| c.yaw == 2.0 && c.pitch == 0.2 && c.distance == 80.0), "{cams:?}");
|
||||
// Without one: view.apply's camera as it is; and another camera draws another picture.
|
||||
super::animation::export_with(&s, &base, Some(&record)).unwrap();
|
||||
assert!(seen.lock().unwrap().iter().all(|c| Some(*c) == s.camera));
|
||||
let pictures = |camera: Value| {
|
||||
let folder = dir.join(format!("p{}", camera["yaw"]));
|
||||
let mut p = with(camera);
|
||||
p["path"] = json!(folder.to_string_lossy());
|
||||
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
std::fs::read(folder.join("frame-0001.png")).unwrap()
|
||||
};
|
||||
assert_ne!(pictures(json!({"yaw": 0.3})), pictures(json!({"yaw": 1.3})));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_animation_params_are_refused() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]}));
|
||||
let dir = out_dir("hostile");
|
||||
let gif = dir.join("x.gif").to_string_lossy().to_string();
|
||||
let base = json!({"study": "Push", "path": gif, "samples": 2, "width": 16, "height": 16});
|
||||
let refused = |change: Value| {
|
||||
let mut p = base.clone();
|
||||
if let (Some(p), Some(change)) = (p.as_object_mut(), change.as_object()) {
|
||||
for (k, v) in change {
|
||||
if v.is_null() {
|
||||
p.remove(k);
|
||||
} else {
|
||||
p.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
super::animation::export_with(&s, &p, Some(&cpu)).err().map(|e| e.to_string())
|
||||
};
|
||||
for change in [
|
||||
json!({"samples": 0}),
|
||||
json!({"samples": 1}),
|
||||
json!({"samples": 1e9}),
|
||||
json!({"samples": "many"}),
|
||||
json!({"samples": 1001}),
|
||||
json!({"width": 1e9}),
|
||||
json!({"width": -16}),
|
||||
json!({"height": 3}),
|
||||
json!({"height": f64::MAX}),
|
||||
json!({"fps": 0}),
|
||||
json!({"fps": 1e9}),
|
||||
json!({"path": ""}),
|
||||
json!({"path": null}),
|
||||
json!({"path": "one.png"}),
|
||||
json!({"path": "a\u{0}b.gif"}),
|
||||
json!({"path": "x".repeat(5000)}),
|
||||
json!({"camera": "iso"}),
|
||||
json!({"camera": {"distance": -1}}),
|
||||
json!({"camera": {"distance": 1e300}}),
|
||||
json!({"camera": {"pitch": 4}}),
|
||||
json!({"camera": {"fov": 9}}),
|
||||
json!({"camera": {"target": [1, 2]}}),
|
||||
json!({"camera": {"fit": true}}),
|
||||
json!({"grid": "no"}),
|
||||
json!({"axes": 1}),
|
||||
json!({"study": null}),
|
||||
json!({"study": "Nope"}),
|
||||
json!({"study": null, "joint": "Rail"}),
|
||||
// 4096 × 4096 frames: a GIF holds four of them.
|
||||
json!({"width": 4096, "height": 4096, "samples": 5}),
|
||||
] {
|
||||
assert!(refused(change.clone()).is_some(), "{change} was accepted");
|
||||
}
|
||||
let e = refused(json!({"width": 4096, "height": 4096, "samples": 5})).unwrap();
|
||||
assert!(e.contains("2…4 for 4096 × 4096"), "{e}");
|
||||
assert!(super::animation::export_with(&s, &base, None).unwrap_err().to_string().contains("no renderer"));
|
||||
assert!(!std::path::Path::new(&gif).exists(), "nothing refused was written");
|
||||
// An agent's export lands only inside its folders.
|
||||
let root = dir.join("root");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
solidcraft_io::vfs::scoped(Some(solidcraft_io::vfs::PathScope::new([root.clone()])), || {
|
||||
let e = refused(json!({"path": dir.join("out").to_string_lossy()})).unwrap();
|
||||
assert!(e.contains("outside the folders this agent may use"), "{e}");
|
||||
assert!(refused(json!({"path": root.join("in.gif").to_string_lossy()})).is_none());
|
||||
});
|
||||
assert!(root.join("in.gif").exists() && !dir.join("out").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -66,22 +66,6 @@ fn instance_selection_survives_rename_move_capture_and_serde() {
|
||||
assert_eq!(roundtrip, s.selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn component_rename_carries_into_placement_names() {
|
||||
// #1665: the browser row shows the placement's name, so a rename has to reach it.
|
||||
let mut s = Session::default();
|
||||
let (component, first) = created(&mut s, "Block");
|
||||
let second = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20,0,0]}))["occurrence"].as_u64().unwrap();
|
||||
let third = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [40,0,0]}))["occurrence"].as_u64().unwrap();
|
||||
let name = |s: &Session, id: u64| s.doc.occurrences.iter().find(|o| o.id == id).unwrap().name.clone();
|
||||
assert_eq!(name(&s, second), "Block:2");
|
||||
// A placement named otherwise (an import's own name) keeps it.
|
||||
s.doc_mut().occurrences.iter_mut().find(|o| o.id == third).unwrap().name = "Blockade:3".into();
|
||||
run(&mut s, "component.rename", json!({"component": component, "name": "box"}));
|
||||
assert_eq!([name(&s, first), name(&s, second), name(&s, third)], ["box:1", "box:2", "Blockade:3"]);
|
||||
assert_eq!(run(&mut s, "component.list", json!({}))["components"][0]["children"][0]["name"], "box:1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_selection_delete_removes_only_selected_instance() {
|
||||
let mut s = Session::default();
|
||||
|
||||
@@ -1463,10 +1463,10 @@ pub(super) fn apply_in_order(sk: &mut Sketch, rep: &SolveReport, first: &[Ent],
|
||||
if !second_locked {
|
||||
ordered(first, second);
|
||||
}
|
||||
// Each first entity that can move may (a free symmetry line between two fixed lines, #1796),
|
||||
// even when another of them can't.
|
||||
for f in first.iter().filter(|f| !ent_locked(sk, rep, **f)) {
|
||||
ordered(&[second], *f);
|
||||
if !first_locked {
|
||||
for f in first {
|
||||
ordered(&[second], *f);
|
||||
}
|
||||
}
|
||||
const TEMP: &str = "__keep_size";
|
||||
for (h, extra) in tries {
|
||||
|
||||
@@ -283,23 +283,3 @@ fn an_angle_between_lines_takes_the_reading_nearest_its_value_and_reports_degree
|
||||
let d = run(&mut s, "sketch.dimension", json!({"entities": ["l2"], "driven": true}));
|
||||
assert_eq!(d["unit"], "mm", "{d}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symmetry_moves_a_free_line_between_two_fixed_lines() {
|
||||
// #1796: with both mirrored lines fixed, the symmetry line between them (a free construction
|
||||
// line) is the one to move; it was refused as "neither entity can move".
|
||||
let mut s = new_sketch();
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 0], [0, 20]], "ids": ["left"]}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[10, 0], [10, 20]], "ids": ["right"]}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[3, 0], [3, 20]], "construction": true, "ids": ["mid"]}));
|
||||
run(&mut s, "sketch.constraint.fix", json!({"entities": ["left", "right"]}));
|
||||
run(&mut s, "sketch.constraint.symmetry", json!({"a": "left", "b": "right", "line": "mid"}));
|
||||
let sk = sketch(&s);
|
||||
let at = |r: &str| sk.point(sk.resolve_point(r).unwrap()).unwrap();
|
||||
for end in ["mid.start", "mid.end"] {
|
||||
assert!((at(end).x - 5.0).abs() < 1e-7, "{end} at {:?}", at(end));
|
||||
}
|
||||
for (end, x) in [("left.start", 0.0), ("left.end", 0.0), ("right.start", 10.0), ("right.end", 10.0)] {
|
||||
assert!((at(end).x - x).abs() < 1e-9, "{end} moved to {:?}", at(end));
|
||||
}
|
||||
}
|
||||
@@ -88,10 +88,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.at("SKETCH", "MODIFY")
|
||||
.icon("blend")
|
||||
.enabled(in_sketch)
|
||||
.params(concat!(
|
||||
"a, b: end points of two curves (\"l1.end\", \"a2.start\"), continuity?: g1|g2|g3|g4 (default g1: a tangent spline; g2…g4 match the reference curves' curvature, curvature rate and 4th derivative as well, as one Bézier of degree 5, 7 or 9)",
|
||||
created_doc!()
|
||||
)),
|
||||
.params(concat!("a, b: end points of two curves (\"l1.end\", \"a2.start\"): a smooth (tangent) spline joining them", created_doc!())),
|
||||
CommandSpec::new("sketch.centerline", "Centerline", centerline)
|
||||
.at("SKETCH", "CREATE")
|
||||
.icon("centerline")
|
||||
@@ -402,68 +399,8 @@ fn end_of(sk: &Sketch, pi: usize) -> Option<(usize, Vec2)> {
|
||||
sk.curves.iter().enumerate().filter(|(_, c)| !c.construction).find_map(|(i, _)| leaving_dir(sk, i, pi).map(|d| (i, d)))
|
||||
}
|
||||
|
||||
/// The continuity a blend asks for: the number of derivatives of each reference curve it
|
||||
/// matches at both joints (g1 is the tangent construction the tool has always made).
|
||||
fn blend_order(p: &Value, cmd: &str) -> Result<usize> {
|
||||
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")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Negate the odd-order derivatives: how a curve's derivatives change when it is read backwards.
|
||||
fn flip_odd(d: &mut [Vec2]) {
|
||||
for (i, v) in d.iter_mut().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
*v = -*v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Derivatives 1…`order` of curve `ci`'s continuation through its end point `pi`, in the
|
||||
/// parameterisation the blend needs at that joint: at the blend's start (`leaving`) the curve's
|
||||
/// continuation runs away from it, at the blend's end the blend runs into the curve instead, which
|
||||
/// is the same curve read backwards. The derivatives are those of the one exact piece that ends
|
||||
/// at `pi`, evaluated at that piece's own end, so an arc gives its circular-motion terms (zero
|
||||
/// curvature rate included) and a conic the quotient rule's terms. Errors when the curve has no
|
||||
/// exact piece, when a derivative is not finite (a corrupt or degenerate reference), or when it
|
||||
/// has no tangent at all: no blend can meet the last case.
|
||||
fn joint_derivatives(sk: &Sketch, ci: usize, pi: usize, order: usize, leaving: bool, what: &str, cmd: &str) -> Result<Vec<Vec2>> {
|
||||
let id = sk.curves.get(ci).map(|c| c.id.as_str()).unwrap_or("?");
|
||||
let (start, end) = sk.curves.get(ci).and_then(|c| c.kind.ends()).ok_or_else(|| bad(cmd, format!("`{id}` has no end points")))?;
|
||||
let at_end = end == pi;
|
||||
if !at_end && start != pi {
|
||||
return Err(bad(cmd, format!("`{what}` is not an end point of `{id}`")));
|
||||
}
|
||||
let pieces = sk.exact_pieces(ci);
|
||||
let seg = if at_end { pieces.last() } else { pieces.first() }.ok_or_else(|| bad(cmd, format!("`{id}` has no exact geometry")))?;
|
||||
let mut d = seg
|
||||
.derivatives(if at_end { 1.0 } else { 0.0 }, order)
|
||||
.ok_or_else(|| bad(cmd, format!("`{id}` has no finite derivatives up to order {order} at `{what}`")))?;
|
||||
// Reading the piece against its own direction, or reading the continuation into the curve
|
||||
// rather than out of it, each reverse the parameterisation once and so flip the odd
|
||||
// derivatives: the blend's start wants the continuation away from the reference's end (no
|
||||
// flip) or backwards out of its start (flip); its end wants the mirror image of that, so a
|
||||
// joint needs a flip exactly when its two readings disagree.
|
||||
if at_end != leaving {
|
||||
flip_odd(&mut d);
|
||||
}
|
||||
if !d.first().is_some_and(|t| t.len() > 0.0) {
|
||||
return Err(bad(cmd, format!("`{id}` has no tangent at `{what}`")));
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "sketch.blend_curve";
|
||||
let order = blend_order(p, cmd)?;
|
||||
let (out, info) = edit(s, p, cmd, false, |sk, _| {
|
||||
let pa = req_parg(sk, p, "a", cmd)?.idx().ok_or_else(|| bad(cmd, "`a` must be the end point of a curve"))?;
|
||||
let pb = req_parg(sk, p, "b", cmd)?.idx().ok_or_else(|| bad(cmd, "`b` must be the end point of a curve"))?;
|
||||
@@ -475,34 +412,10 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "the ends must differ"));
|
||||
}
|
||||
let first_new = sk.points.len();
|
||||
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 cons = vec![add_c(sk, ConstraintKind::Tangent { a: ca, b: sp })?, add_c(sk, ConstraintKind::Tangent { a: cb, b: sp })?];
|
||||
(sp, cons)
|
||||
} else {
|
||||
// One Bézier of degree 2·order + 1 whose controls are the Hermite interpolation of the
|
||||
// two references' derivatives, so its 1st…order-th derivatives are theirs at both
|
||||
// joints. Tangency comes from the construction, so it needs no tangent constraints.
|
||||
let da = joint_derivatives(sk, ca, pa, order, true, "a", cmd)?;
|
||||
let db = joint_derivatives(sk, cb, pb, order, false, "b", cmd)?;
|
||||
let mut pts: Vec<usize> = Vec::with_capacity(2 * order + 2);
|
||||
let cps = solidcraft_geom::hermite_bezier(qa, qb, &da, &db)
|
||||
.ok_or_else(|| bad(cmd, "the blend curve could not be built from the derivatives of `a` and `b`"))?;
|
||||
for (i, q) in cps.iter().enumerate() {
|
||||
pts.push(if i == 0 {
|
||||
pa
|
||||
} else if i + 1 == cps.len() {
|
||||
pb
|
||||
} else {
|
||||
sk.add_point(*q, None)?
|
||||
});
|
||||
}
|
||||
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)?;
|
||||
(sp, Vec::new())
|
||||
};
|
||||
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 cons = vec![add_c(sk, ConstraintKind::Tangent { a: ca, b: sp })?, add_c(sk, ConstraintKind::Tangent { a: cb, b: sp })?];
|
||||
solve_new_only(sk, first_new);
|
||||
Ok((ids_of(sk, &[sp]), cons))
|
||||
})?;
|
||||
@@ -947,391 +860,3 @@ 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 solidcraft_sketch::CurveKind;
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<String> {
|
||||
v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn new_sketch() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY"}));
|
||||
s
|
||||
}
|
||||
|
||||
fn sketch(s: &Session) -> solidcraft_sketch::Sketch {
|
||||
let id = s.active_sketch.unwrap();
|
||||
s.model.state().sketch(id).unwrap().sketch.clone()
|
||||
}
|
||||
|
||||
fn factorial(n: usize) -> f64 {
|
||||
(1..=n).fold(1.0, |a, b| a * b as f64)
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
fn piece_derivatives(seg: &Seg2, at_end: bool, order: usize) -> Vec<Vec2> {
|
||||
let t = if at_end { 1.0 } else { 0.0 };
|
||||
let p = seg.point_at(t);
|
||||
let mut d = match *seg {
|
||||
Seg2::Line { a, b } => vec![b - a, Vec2::ZERO, Vec2::ZERO, Vec2::ZERO],
|
||||
Seg2::Arc { center, sweep, .. } => {
|
||||
let (v, s2) = (seg.derivative(t), sweep * sweep);
|
||||
vec![v, (p - center) * -s2, v * -s2, (p - center) * (s2 * s2)]
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
let third = (p3 - p2 * 3.0 + p1 * 3.0 - p0) * 6.0;
|
||||
if at_end {
|
||||
vec![(p3 - p2) * 3.0, (p3 - p2 * 2.0 + p1) * 6.0, third, Vec2::ZERO]
|
||||
} else {
|
||||
vec![(p1 - p0) * 3.0, (p0 - p1 * 2.0 + p2) * 6.0, third, Vec2::ZERO]
|
||||
}
|
||||
}
|
||||
Seg2::Conic { a, apex, b, w } => {
|
||||
// The rational quadratic's numerator N and weight D as quadratics in the power
|
||||
// basis; dividing N's series by D's (constant term 1 at both ends) has to give the
|
||||
// Taylor coefficients of the curve.
|
||||
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 h = 1e-3;
|
||||
let series = |f: &dyn Fn(f64) -> Vec2| [f(t), (f(t + h) - f(t - h)) / (2.0 * h), (f(t + h) - f(t) * 2.0 + f(t - h)) / (2.0 * h * h)];
|
||||
let n = series(&|x| n0 + n1 * x + n2 * (x * x));
|
||||
let den = [1.0 + e1 * t + e2 * (t * t), e1 + e2 * (2.0 * t), e2];
|
||||
let mut x = vec![n[0] / den[0]];
|
||||
for j in 1..=order {
|
||||
let mut v = n.get(j).copied().unwrap_or(Vec2::ZERO);
|
||||
for i in 1..=j {
|
||||
v -= x[j - i] * den.get(i).copied().unwrap_or(0.0);
|
||||
}
|
||||
x.push(v / den[0]);
|
||||
}
|
||||
x.remove(0);
|
||||
x.into_iter().enumerate().map(|(i, v)| v * factorial(i + 1)).collect()
|
||||
}
|
||||
Seg2::Bezier { .. } => panic!("a test piece is not a high-degree Bézier"),
|
||||
};
|
||||
d.truncate(order);
|
||||
d
|
||||
}
|
||||
|
||||
/// The derivatives 1…`order` the blend's own control polygon carries at an end: the j-th
|
||||
/// difference of the controls, scaled by `n!/(n − j)!` (the Bézier endpoint identity).
|
||||
fn blend_derivatives(ctrl: &[Vec2], at_end: bool, order: usize) -> Vec<Vec2> {
|
||||
let c: Vec<Vec2> = if at_end { ctrl.iter().rev().copied().collect() } else { ctrl.to_vec() };
|
||||
let n = c.len() - 1;
|
||||
let (mut diffs, mut scale) = (c, 1.0);
|
||||
let mut out = Vec::new();
|
||||
for j in 1..=order {
|
||||
diffs = diffs.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
scale *= (n + 1 - j) as f64;
|
||||
out.push(diffs.first().copied().unwrap_or_default() * scale);
|
||||
}
|
||||
if at_end {
|
||||
for (i, v) in out.iter_mut().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
*v = -*v;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The blend curve's control points, its degree and the one exact piece they make.
|
||||
fn blend_of(s: &Session, id: &str) -> (Vec<Vec2>, usize, Seg2) {
|
||||
let sk = sketch(s);
|
||||
let ci = sk.curve_index(id).unwrap();
|
||||
let ctrl: Vec<Vec2> = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect();
|
||||
let degree = match sk.curves[ci].kind {
|
||||
CurveKind::Spline { degree, .. } => usize::from(degree),
|
||||
ref other => panic!("{other:?}"),
|
||||
};
|
||||
let pieces = sk.exact_pieces(ci);
|
||||
assert_eq!(pieces.len(), 1, "{pieces:?}");
|
||||
(ctrl, degree, pieces[0])
|
||||
}
|
||||
|
||||
/// The reference pair the tests build: a line `(0, 0)`–`(6, 0)` ending at `a` and a three-point
|
||||
/// control spline starting at `b`, so the blend runs out of the first and into the second with
|
||||
/// no reversal at either joint.
|
||||
fn two_references(s: &mut Session) -> (String, String, [Vec2; 4]) {
|
||||
let a = ids(&run(s, "sketch.line", json!({"points": [[0, 0], [6, 0]]}))["curves"])[0].clone();
|
||||
let bctrl = [Vec2::new(20.0, 10.0), Vec2::new(24.0, 14.0), Vec2::new(30.0, 9.0), Vec2::new(34.0, 6.0)];
|
||||
let b = ids(&run(s, "sketch.spline.control_point", json!({"points": [[20, 10], [24, 14], [30, 9], [34, 6]]}))["curves"])[0].clone();
|
||||
(a, b, bctrl)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_matches_both_references_through_the_requested_order() {
|
||||
for order in 1..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, bctrl) = two_references(&mut s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1, "g{order} is one Bézier of degree 2k+1");
|
||||
assert_eq!(ctrl.len(), 2 * order + 2, "g{order} control count");
|
||||
assert!(r["sketch"]["solved"].as_bool().unwrap_or(false), "{r}");
|
||||
assert!(piece.start().dist(Vec2::new(6.0, 0.0)) < 1e-12 && piece.end().dist(bctrl[0]) < 1e-12, "the blend joins `a` and `b`");
|
||||
|
||||
// What each reference supplies at the joint: the line's own derivative at its end (and
|
||||
// nothing higher) and the cubic's at its start.
|
||||
let line = piece_derivatives(&Seg2::Line { a: Vec2::ZERO, b: Vec2::new(6.0, 0.0) }, true, 4);
|
||||
let cubic = piece_derivatives(&Seg2::Cubic { p0: bctrl[0], p1: bctrl[1], p2: bctrl[2], p3: bctrl[3] }, false, 4);
|
||||
let got0 = blend_derivatives(&ctrl, false, 4);
|
||||
let got1 = blend_derivatives(&ctrl, true, 4);
|
||||
// g1 is the tangent construction of the tool: the first derivative is parallel to the
|
||||
// reference's (that is what G1 is), with the tool's own chord-scaled magnitude. g2 and
|
||||
// up match the reference's derivative vectors themselves.
|
||||
let tan_line = line[0].normalized().unwrap();
|
||||
let tan_cubic = cubic[0].normalized().unwrap();
|
||||
assert!(got0[0].cross(tan_line).abs() < 1e-9 && got0[0].dot(tan_line) > 0.0, "g{order} leaves `a` along {tan_line:?}, not {:?}", got0[0]);
|
||||
assert!(
|
||||
got1[0].cross(tan_cubic).abs() < 1e-9 && got1[0].dot(tan_cubic) > 0.0,
|
||||
"g{order} enters `b` along {tan_cubic:?}, not {:?}",
|
||||
got1[0]
|
||||
);
|
||||
for j in 1..order {
|
||||
assert!(got0[j].dist(line[j]) < 1e-9, "g{order} at a, order {}: {:?} vs {:?}", j + 1, got0[j], line[j]);
|
||||
assert!(got1[j].dist(cubic[j]) < 1e-9, "g{order} at b, order {}: {:?} vs {:?}", j + 1, got1[j], cubic[j]);
|
||||
}
|
||||
if order >= 2 {
|
||||
for (got, want) in [(got0[0], line[0]), (got1[0], cubic[0])] {
|
||||
assert!(got.dist(want) < 1e-9, "g{order} matches the reference's own derivative: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
// The next order up is not met: the line has no derivative there at all, while a blend of
|
||||
// degree 2k+1 has.
|
||||
if order < 4 {
|
||||
let next = got0[order];
|
||||
assert!(next.dist(line[order]) > 1e-6, "g{order} matched one order too many at a: {next:?}");
|
||||
}
|
||||
// Curvature itself (orientation-free, from finite differences of the samples) agrees at
|
||||
// both joints once the order asks for it.
|
||||
if order >= 2 {
|
||||
let curve = |x: f64| piece.point_at(x.clamp(0.0, 1.0));
|
||||
let line_f = |x: f64| Vec2::new(6.0 * x, 0.0);
|
||||
let cubic_f = |x: f64| Seg2::Cubic { p0: bctrl[0], p1: bctrl[1], p2: bctrl[2], p3: bctrl[3] }.point_at(x);
|
||||
let k0 = solidcraft_sketch::end_curvature(&curve, false);
|
||||
let ka = solidcraft_sketch::end_curvature(&line_f, true);
|
||||
let k1 = solidcraft_sketch::end_curvature(&curve, true);
|
||||
let kb = solidcraft_sketch::end_curvature(&cubic_f, false);
|
||||
assert!(k0.dist(ka) < 1e-3, "g{order} curvature at a: {k0:?} vs {ka:?}");
|
||||
assert!(k1.dist(kb) < 1e-3, "g{order} curvature at b: {k1:?} vs {kb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_g1_is_the_tangent_construction_with_its_constraints() {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, bctrl) = two_references(&mut s);
|
||||
let r = run(&mut s, "sketch.blend_curve", json!({"a": format!("{a}.end"), "b": format!("{b}.start")}));
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, _) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 3, "the default is the cubic tangent spline");
|
||||
let (qa, qb) = (Vec2::new(6.0, 0.0), bctrl[0]);
|
||||
let l = qa.dist(qb);
|
||||
let tb = (qb - bctrl[1]).normalized().unwrap();
|
||||
let want = [qa, qa + Vec2::X * (l / 3.0), qb + tb * (l / 3.0), qb];
|
||||
for (i, q) in want.iter().enumerate() {
|
||||
assert!(ctrl[i].dist(*q) < 1e-9, "g1 control {i}: {:?} vs {q:?}", ctrl[i]);
|
||||
}
|
||||
assert_eq!(ids(&r["constraints"]).len(), 2, "the two tangents are kept: {r}");
|
||||
// g2…g4 meet the derivatives by construction and need no constraint of their own.
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, _) = two_references(&mut s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
assert!(ids(&r["constraints"]).is_empty(), "g{order}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_between_two_lines_is_curvature_free_to_the_requested_order() {
|
||||
// Two lines meeting at a right angle: from G2 on, the blend has the lines' own zero
|
||||
// curvature at both joints (a corner with no curvature jump).
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 10], [20, 12]]}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1);
|
||||
let got0 = blend_derivatives(&ctrl, false, 4);
|
||||
let got1 = blend_derivatives(&ctrl, true, 4);
|
||||
assert!(got0[0].dist(Vec2::new(2.0, 0.0)) < 1e-12, "g{order} leaves `a` along +x: {:?}", got0[0]);
|
||||
assert!(got1[0].dist(Vec2::new(0.0, 2.0)) < 1e-12, "g{order} enters `b` along +y: {:?}", got1[0]);
|
||||
for j in 1..order {
|
||||
assert!(got0[j].len() < 1e-12, "g{order}: a line has no order-{} derivative", j + 1);
|
||||
assert!(got1[j].len() < 1e-12, "g{order}: a line has no order-{} derivative", j + 1);
|
||||
}
|
||||
if order < 4 {
|
||||
assert!(got0[order].len() > 1e-6, "g{order}: the blend curves, the line does not");
|
||||
}
|
||||
assert!(piece.start().dist(Vec2::new(2.0, 0.0)) < 1e-12 && piece.end().dist(Vec2::new(20.0, 10.0)) < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_matches_a_conic_reference() {
|
||||
for order in 2..=4usize {
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.conic", json!({"start": [20, 10], "apex": [26, 16], "end": [30, 10], "rho": 0.7}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": format!("g{order}"),
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, _) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 2 * order + 1);
|
||||
// The conic's own derivatives at its start: `w` comes from the sketch's `rho`, and the
|
||||
// series division in `piece_derivatives` is the expectation.
|
||||
let w = 0.7 / (1.0 - 0.7);
|
||||
let conic = Seg2::Conic { a: Vec2::new(20.0, 10.0), apex: Vec2::new(26.0, 16.0), b: Vec2::new(30.0, 10.0), w };
|
||||
let want = piece_derivatives(&conic, false, order);
|
||||
let got = blend_derivatives(&ctrl, true, order);
|
||||
for j in 0..order {
|
||||
assert!(got[j].dist(want[j]) < 1e-8 * want[j].len().max(1.0), "g{order} order {}: {:?} vs {:?}", j + 1, got[j], want[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_refuses_hostile_orders_and_degenerate_references() {
|
||||
let mut s = new_sketch();
|
||||
let (a, b, _) = two_references(&mut s);
|
||||
let ends = json!({"a": format!("{a}.end"), "b": format!("{b}.start")});
|
||||
for (order, want) in [("g0", true), ("g9", true), ("G9", true), ("curvature", true), ("", false), ("g2", false), ("G4", false)] {
|
||||
let mut p = ends.clone();
|
||||
p["continuity"] = json!(order);
|
||||
let r = s.execute("sketch.blend_curve", &p);
|
||||
assert_eq!(r.is_err(), want, "continuity {order:?}: {r:?}");
|
||||
assert!(r.is_ok() || r.unwrap_err().to_string().contains("continuity"), "continuity {order:?} needs a clear error");
|
||||
}
|
||||
let mut numbered = ends.clone();
|
||||
numbered["continuity"] = json!(3);
|
||||
assert!(s.execute("sketch.blend_curve", &numbered).is_err(), "a number is not a continuity");
|
||||
// A point that is not an end of a curve, and the same end twice.
|
||||
let p = ids(&run(&mut s, "sketch.point", json!({"point": [50, 50]}))["created"]["points"])[0].clone();
|
||||
let e = s.execute("sketch.blend_curve", &json!({"a": p, "b": format!("{b}.start")})).unwrap_err().to_string();
|
||||
assert!(e.contains("no curve ends at `a`"), "{e}");
|
||||
let e = s.execute("sketch.blend_curve", &json!({"a": format!("{a}.end"), "b": format!("{a}.end")})).unwrap_err().to_string();
|
||||
assert!(e.contains("ends must differ"), "{e}");
|
||||
// The helper behind the command refuses a corrupt (non-finite) reference and a reference
|
||||
// with no tangent at all, never guessing at them.
|
||||
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();
|
||||
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 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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_curve_with_g4_closes_a_profile_that_measures_exactly() {
|
||||
// A quarter-turn blend from (2, 0) into a line at (20, 10), closed by the chord between its
|
||||
// ends: the region's area comes from the degree-9 curve, not from its chord.
|
||||
let mut s = new_sketch();
|
||||
let a = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [2, 0]]}))["curves"])[0].clone();
|
||||
let b = ids(&run(&mut s, "sketch.line", json!({"points": [[20, 10], [20, 12]]}))["curves"])[0].clone();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"sketch.blend_curve",
|
||||
json!({
|
||||
"a": format!("{a}.end"),
|
||||
"b": format!("{b}.start"),
|
||||
"continuity": "g4",
|
||||
}),
|
||||
);
|
||||
let sp = ids(&r["curves"])[0].clone();
|
||||
let (ctrl, degree, piece) = blend_of(&s, &sp);
|
||||
assert_eq!(degree, 9, "G4 is one degree-9 Bézier");
|
||||
assert_eq!(ctrl.len(), 10);
|
||||
// The command still reports what it added, with stable ids: ten controls of which the two
|
||||
// joints are the references' own points, so eight new points, and no new constraint.
|
||||
assert_eq!(ids(&r["created"]["curves"]), vec![sp.clone()], "{r}");
|
||||
assert_eq!(ids(&r["created"]["points"]).len(), 8, "{r}");
|
||||
assert!(ids(&r["created"]["constraints"]).is_empty() && ids(&r["created"]["dimensions"]).is_empty(), "{r}");
|
||||
run(&mut s, "sketch.line", json!({"points": [[20, 10], [2, 0]], "id": "chord"}));
|
||||
// Drop the two references: what is left is the blend and its chord, one closed region.
|
||||
run(&mut s, "sketch.delete", json!({"entities": [a, b]}));
|
||||
let id = s.active_sketch.unwrap();
|
||||
let state = s.model.state();
|
||||
let profiles = &state.sketch(id).unwrap().profiles;
|
||||
assert_eq!(profiles.len(), 1, "the blend and the chord close one region");
|
||||
let area = profiles[0].area;
|
||||
// A fine sampling of the exact piece plus the straight chord reproduces the area; the chord
|
||||
// alone (what a polyline approximation would give) is exactly zero.
|
||||
let n = 20_000;
|
||||
let mut sampled = 0.0;
|
||||
for i in 0..n {
|
||||
let (t0, t1) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
|
||||
sampled += 0.5 * piece.point_at(t0).cross(piece.point_at(t1));
|
||||
}
|
||||
// The chord back from (20, 10) to (2, 0) contributes its own shoelace term; together they
|
||||
// are the region.
|
||||
sampled += 0.5 * Vec2::new(20.0, 10.0).cross(Vec2::new(2.0, 0.0));
|
||||
assert!((area - sampled.abs()).abs() < 1e-4, "{area} vs {sampled}");
|
||||
assert!(area > 1e-2, "the blend curves away from the chord: {area}");
|
||||
// And the degree-9 profile still extrudes to its area times the height (the kernel's
|
||||
// volume of a free-form body is a numerical integration, so this is the same 2e-4 the
|
||||
// neighbouring free-form extrusion test allows).
|
||||
run(&mut s, "solid.extrude", json!({"distance": 5}));
|
||||
let m = run(&mut s, "inspect.measure", json!({}));
|
||||
let volume = m["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((volume - area * 5.0).abs() / (area * 5.0) < 2e-4, "volume {volume} vs {}", area * 5.0);
|
||||
assert!(m["bodies"][0]["faces"].as_u64().unwrap_or(0) >= 3, "a solid with the blend as a side: {m}");
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,6 @@ use solidcraft_sketch::{Shape, intersections};
|
||||
|
||||
use crate::{Result, params::bad};
|
||||
|
||||
/// Degrees the exact extend intersection handles: a round support squares the piece's degree in
|
||||
/// homogeneous form, and both the root finder and its `evaluate` buffer hold at most 15
|
||||
/// coefficients, so 2·7 + 1 fits.
|
||||
const MAX_EXACT_EXTEND_DEGREE: u8 = 7;
|
||||
|
||||
fn choose(n: usize, k: usize) -> f64 {
|
||||
(0..k.min(n - k)).fold(1.0, |value, i| value * (n - i) as f64 / (i + 1) as f64)
|
||||
}
|
||||
@@ -118,7 +113,7 @@ pub(super) fn hits(support: &Shape, seg: &Seg2, budget: &mut usize) -> Result<Ve
|
||||
let (points, weights): (Vec<Vec2>, Vec<f64>) = match *seg {
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => (vec![p0, p1, p2, p3], vec![1.0; 4]),
|
||||
Seg2::Conic { a, apex, b, w } if w.is_finite() && w > 0.0 => (vec![a, apex, b], vec![1.0, w, 1.0]),
|
||||
Seg2::Bezier { n, p } if (1..=MAX_EXACT_EXTEND_DEGREE).contains(&n) => (p[..=usize::from(n)].to_vec(), vec![1.0; usize::from(n) + 1]),
|
||||
Seg2::Bezier { n, p } if (1..=7).contains(&n) => (p[..=usize::from(n)].to_vec(), vec![1.0; usize::from(n) + 1]),
|
||||
_ => return Err(bad("sketch.extend", "invalid exact curve piece")),
|
||||
};
|
||||
if points.iter().any(|p| !p.is_finite()) {
|
||||
@@ -200,8 +195,8 @@ mod tests {
|
||||
elevated.push(y[n - 1]);
|
||||
y = elevated;
|
||||
}
|
||||
let mut points = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL];
|
||||
for (i, p) in points.iter_mut().take(8).enumerate() {
|
||||
let mut points = [Vec2::ZERO; 8];
|
||||
for (i, p) in points.iter_mut().enumerate() {
|
||||
*p = Vec2::new(10.0 + i as f64 * 20.0 / 7.0, y[i]);
|
||||
}
|
||||
let target = Seg2::Bezier { n: 7, p: points };
|
||||
|
||||
@@ -51,7 +51,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("surface.loft", "Surface Loft", surface_loft)
|
||||
.at("SURFACE", "CREATE")
|
||||
.icon("surface_loft")
|
||||
.params("sections: [{sketch, curves?: [curve ids], profiles?} | {body, edges: [[x,y,z]]}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed; a body edge chain takes the face the chain bounds as the surface the end repeats); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g0: how much of the surface at the first and last section the loft repeats — the tangent plane, the curvature, or how that curvature changes); crown?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"),
|
||||
.params("sections: [{sketch, curves?: [curve ids], profiles?}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"),
|
||||
CommandSpec::new("surface.offset", "Offset Surface", offset)
|
||||
.at("SURFACE", "CREATE")
|
||||
.icon("surface_offset")
|
||||
@@ -369,57 +369,15 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let mut sections = Vec::with_capacity(given.len());
|
||||
for sec in given {
|
||||
// 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<solidcraft_geom::Vec3> =
|
||||
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"));
|
||||
}
|
||||
if sec.get("sketch").is_some() {
|
||||
return Err(bad(cmd, "a section is either a sketch chain or a body edge chain"));
|
||||
}
|
||||
sections.push(solidcraft_doc::SheetSection {
|
||||
sketch: SketchId(0),
|
||||
profiles: None,
|
||||
curves: Vec::new(),
|
||||
body: Some(BodyName::from(body.to_string())),
|
||||
edges: edges.into_iter().map(Position).collect(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let sketch = sketch_id(s, sec.get("sketch"), cmd, "sections.sketch")?;
|
||||
let curves = string_list(sec, "curves");
|
||||
if curves.len() > 1000 {
|
||||
return Err(bad(cmd, "at most 1000 curves a section"));
|
||||
}
|
||||
let profiles = if sec.get("profiles").is_some() { Some(profiles(sec, cmd)?) } else { None };
|
||||
sections.push(solidcraft_doc::SheetSection { sketch: SketchId(sketch), profiles, curves, body: None, edges: Vec::new() });
|
||||
sections.push(solidcraft_doc::SheetSection { sketch: SketchId(sketch), profiles, curves });
|
||||
}
|
||||
let continuity = match p.get("continuity") {
|
||||
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<Continuity> {
|
||||
x.and_then(Value::as_str).and_then(Continuity::parse).ok_or_else(|| bad(cmd, "`continuity` entries must be g0, g1, g2 or g3"))
|
||||
};
|
||||
[word(list.first())?, word(list.get(1))?]
|
||||
}
|
||||
};
|
||||
let crown = match p.get("crown") {
|
||||
None | Some(Value::Null) => [0.0, 0.0],
|
||||
Some(v) => {
|
||||
let list = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, "`crown` must be two numbers, one per end"))?;
|
||||
let one = |x: Option<&Value>| -> Result<f64> {
|
||||
x.and_then(Value::as_f64)
|
||||
.filter(|x| x.is_finite() && (-0.9..=3.0).contains(x))
|
||||
.ok_or_else(|| bad(cmd, "each `crown` entry must be between -0.9 (flattest) and 3 (fullest)"))
|
||||
};
|
||||
[one(list.first())?, one(list.get(1))?]
|
||||
}
|
||||
};
|
||||
add_feature(s, p, FeatureKind::SurfaceLoft { sections, continuity, crown })
|
||||
add_feature(s, p, FeatureKind::SurfaceLoft { sections })
|
||||
}
|
||||
|
||||
fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1254,7 +1212,7 @@ mod tests {
|
||||
/// as it was.
|
||||
#[test]
|
||||
fn planned_commands_refuse_and_leave_the_design_alone() {
|
||||
let planned = ["surface.fillet"];
|
||||
let planned = ["surface.fillet", "inspect.continuity"];
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "B"}));
|
||||
let before = s.doc.features.len();
|
||||
@@ -1630,68 +1588,4 @@ mod tests {
|
||||
assert!(s.execute("surface.fair", &json!({"body": "Shell", "iterations": 0, "tolerance": 1.0})).is_err());
|
||||
assert!(s.execute("surface.fair", &json!({"body": "Shell", "tolerance": 0})).is_err());
|
||||
}
|
||||
|
||||
/// A loft through three sections whose first and last are edge chains of two boxes, with
|
||||
/// `continuity: ["g1","g1"]`: it leaves each box's top face tangentially (the run direction
|
||||
/// lies in that face) and passes through the sketch between them.
|
||||
#[test]
|
||||
fn surface_loft_leaves_a_box_face_tangentially() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"corner": [0, 0, 0], "length": 20, "width": 20, "height": 10, "body_name": "Low"}));
|
||||
run(&mut s, "solid.box", json!({"corner": [40, 0, 0], "length": 20, "width": 20, "height": 10, "body_name": "High"}));
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "YZ", "offset": 30, "name": "Mid"}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "Mid", "name": "Bump"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[0, 14], [20, 14]], "ids": ["b"]}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(
|
||||
&mut s,
|
||||
"surface.loft",
|
||||
json!({
|
||||
"sections": [
|
||||
{"body": "Low", "edges": [[20, 5, 10], [20, 15, 10]]},
|
||||
{"sketch": "Bump", "curves": ["b"]},
|
||||
{"body": "High", "edges": [[40, 5, 10], [40, 15, 10]]}
|
||||
],
|
||||
"continuity": ["g1", "g1"],
|
||||
"crown": [0, 0],
|
||||
"body_name": "Blend"
|
||||
}),
|
||||
);
|
||||
let body = s.world_state().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();
|
||||
// The ends lie on the two boxes' top faces, and the sketch is met exactly between them.
|
||||
for p in &grid[0] {
|
||||
assert!((p.z - 10.0).abs() < 1e-9 && (p.x - 20.0).abs() < 1e-9, "the first seam is the box edge: {p:?}");
|
||||
}
|
||||
for p in &grid[1000] {
|
||||
assert!((p.z - 10.0).abs() < 1e-9 && (p.x - 40.0).abs() < 1e-9, "the last seam is the box edge: {p:?}");
|
||||
}
|
||||
for p in &grid[500] {
|
||||
assert!((p.z - 14.0).abs() < 1e-9 && (p.x - 30.0).abs() < 1e-9, "the blend meets the sketch: {p:?}");
|
||||
}
|
||||
// The seam leaves along the box's top face: the run direction the blend is given is what
|
||||
// the face holds, so the tangent there is horizontal and along the run. (The step the grid
|
||||
// takes is a thousandth of the run, and a chord over that step carries an O(h²) bias of
|
||||
// about 0.011 here, so 1e-2 on the rise off the face is what the grid can measure; the
|
||||
// kernel's own tests pin the tangent to the frame's leave direction exactly.)
|
||||
for j in [0usize, 4, 8] {
|
||||
let d = (grid[1][j] - grid[0][j]).normalized().unwrap();
|
||||
assert!(d.z.abs() < 2e-2 && d.x > 0.999, "the blend leaves the low box's top face: {d:?}");
|
||||
let d = (grid[1000][j] - grid[999][j]).normalized().unwrap();
|
||||
assert!(d.z.abs() < 2e-2 && d.x > 0.999, "the blend arrives along the high box's top face: {d:?}");
|
||||
}
|
||||
// Hostile parameters are refused, never panicking.
|
||||
let bad = [
|
||||
json!({"sections": [{"body": "Low", "edges": [[20, 5, 10], [20, 15, 10]]}, {"sketch": "Bump", "curves": ["b"]}], "continuity": ["g1"]}),
|
||||
json!({"sections": [{"body": "Low", "edges": []}, {"sketch": "Bump", "curves": ["b"]}], "continuity": ["g1", "g1"]}),
|
||||
json!({"sections": [{"body": "Low", "edges": [[20, 5, 10]], "sketch": "Bump"}, {"sketch": "Bump", "curves": ["b"]}]}),
|
||||
json!({"sections": [{"sketch": "Bump", "curves": ["b"]}, {"sketch": "Bump", "curves": ["b"]}], "crown": [5, 0]}),
|
||||
json!({"sections": [{"sketch": "Bump", "curves": ["b"]}, {"sketch": "Bump", "curves": ["b"]}], "continuity": ["g9", "g1"]}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("surface.loft", &p).is_err(), "hostile loft params: {p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,8 @@ use serde_json::{Value, json};
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, bool_, num, str_, vec3};
|
||||
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;
|
||||
/// 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;
|
||||
use crate::params::{bad, bool_, num, vec3};
|
||||
use crate::{Result, Session, SurfaceAnalysis};
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("inspect.zebra", "Zebra Analysis", zebra)
|
||||
@@ -45,14 +34,11 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.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; \
|
||||
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); \
|
||||
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",
|
||||
),
|
||||
planned!("inspect.continuity", "Continuity Analysis", "770")
|
||||
.at("SURFACE", "INSPECT")
|
||||
.icon("continuity")
|
||||
.noundo()
|
||||
.params("planned: body?; edges?: [[x,y,z]] (default: every edge of the body); returns each edge's worst gap (G0), normal angle (G1) and curvature jump (G2); clear?: true turns the analysis off"),
|
||||
];
|
||||
|
||||
fn set(s: &mut Session, p: &Value, a: SurfaceAnalysis) -> Result<Value> {
|
||||
@@ -108,214 +94,12 @@ fn curvature_map(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
set(s, p, SurfaceAnalysis::Curvature { radius })
|
||||
}
|
||||
|
||||
/// `inspect.continuity`: measure how far the two faces meeting at each picked edge (or at every
|
||||
/// edge of a body) depart from sharing a curve (G0), a tangent plane (G1) and a curvature (G2),
|
||||
/// and keep the seams so the viewport can shade them. View state only: the design and its undo
|
||||
/// history are untouched (`noundo`), as with the other analyses.
|
||||
fn continuity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "inspect.continuity";
|
||||
if bool_(p, "clear").unwrap_or(false) {
|
||||
s.continuity.clear();
|
||||
s.revision += 1;
|
||||
return Ok(json!({ "analysis": "continuity", "cleared": true }));
|
||||
}
|
||||
let samples = match p.get("samples") {
|
||||
None => 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 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)?,
|
||||
};
|
||||
let picks = edge_picks(p)?;
|
||||
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}`")))?],
|
||||
None => st.bodies.iter().filter(|b| s.body_visible(&b.name)).collect(),
|
||||
};
|
||||
if candidates.is_empty() {
|
||||
return Err(bad(cmd, "there are no visible bodies to analyse: name a `body`"));
|
||||
}
|
||||
if candidates.len() > MAX_BODIES {
|
||||
return Err(bad(cmd, format!("more than {MAX_BODIES} bodies are shown: name the `body` to analyse")));
|
||||
}
|
||||
let mut targets: Vec<(&solidcraft_doc::ModelBody, Vec<usize>)> = Vec::new();
|
||||
if picks.is_empty() {
|
||||
targets.extend(candidates.into_iter().map(|b| (b, Vec::new())));
|
||||
} else {
|
||||
// Picks mean edges of one body (a design may stack bodies at the same place): a list
|
||||
// that lands on one body's edges only is analysed, and anything else is refused.
|
||||
let mut hits = Vec::new();
|
||||
let mut refused = None;
|
||||
for b in candidates {
|
||||
match kernel::pick_edges(&b.body, &picks) {
|
||||
Ok(edges) => hits.push((b, edges)),
|
||||
Err(e) => refused = refused.or(Some(e)),
|
||||
}
|
||||
}
|
||||
if hits.is_empty() {
|
||||
return Err(match (named, refused) {
|
||||
(Some(_), Some(e)) => e.into(),
|
||||
_ => bad(cmd, "no visible body has an edge matching `edges`"),
|
||||
});
|
||||
}
|
||||
if hits.len() > 1 {
|
||||
return Err(bad(cmd, "`edges` matches edges of more than one body: name the `body` to analyse"));
|
||||
}
|
||||
targets.extend(hits);
|
||||
}
|
||||
let mut seams: Vec<ContinuitySeam> = Vec::new();
|
||||
let mut bodies = Vec::new();
|
||||
let mut summary = Summary::default();
|
||||
for (body, edges) in &targets {
|
||||
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 { 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.skipped += report.skipped;
|
||||
summary.unmeasured += report.unmeasured;
|
||||
bodies.push(json!({
|
||||
"body": body.name,
|
||||
"edges": rows,
|
||||
"skipped": report.skipped,
|
||||
"unmeasured": report.unmeasured,
|
||||
}));
|
||||
}
|
||||
s.continuity = seams;
|
||||
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,
|
||||
},
|
||||
"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(),
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
/// A tolerance parameter. A value that is given but unusable (NaN, infinity, negative, a
|
||||
/// string, a bare `null`) is refused: `num` would fold it into "not given".
|
||||
fn tolerance(p: &Value, key: &str, default: f64) -> Result<f64> {
|
||||
match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(v) => match v.as_f64() {
|
||||
Some(x) if x.is_finite() && (0.0..1e9).contains(&x) => Ok(x),
|
||||
_ => Err(bad("inspect.continuity", format!("`{key}` must be a finite number, 0 or more"))),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `edges` parameter: points on the edges to measure, or `{"index": i}` entries in the
|
||||
/// display mesh's edge order. Absent (or an empty list) means every edge of the body.
|
||||
fn edge_picks(p: &Value) -> Result<Vec<kernel::EdgePick>> {
|
||||
let Some(value) = p.get("edges") else { return Ok(Vec::new()) };
|
||||
let Some(list) = value.as_array() else {
|
||||
return Err(bad("inspect.continuity", "`edges` must be a list of [x,y,z] points or {\"index\": i} entries"));
|
||||
};
|
||||
if list.len() > MAX_PICKS {
|
||||
return Err(bad("inspect.continuity", format!("pick at most {MAX_PICKS} edges")));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for item in list {
|
||||
if let Some(index) = item.get("index").and_then(Value::as_u64) {
|
||||
let index = usize::try_from(index).map_err(|_| bad("inspect.continuity", "`index` is too large"))?;
|
||||
out.push(kernel::EdgePick::Index(index));
|
||||
} else if let Some(point) = vec3(item) {
|
||||
out.push(kernel::EdgePick::Point(point));
|
||||
} else {
|
||||
return Err(bad("inspect.continuity", "each `edges` entry is a point [x,y,z] or {\"index\": i}"));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Counts of a continuity reply, and the worst verdict over every edge measured.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct Summary {
|
||||
edges: usize,
|
||||
smooth: usize,
|
||||
curvature_jump: usize,
|
||||
sharp: usize,
|
||||
gap: usize,
|
||||
skipped: usize,
|
||||
unmeasured: usize,
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
fn count(&mut self, verdict: kernel::SeamVerdict) {
|
||||
self.edges += 1;
|
||||
match verdict {
|
||||
kernel::SeamVerdict::Smooth => self.smooth += 1,
|
||||
kernel::SeamVerdict::CurvatureJump => self.curvature_jump += 1,
|
||||
kernel::SeamVerdict::Sharp => self.sharp += 1,
|
||||
kernel::SeamVerdict::Gap => self.gap += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<kernel::SeamVerdict> {
|
||||
[
|
||||
(self.smooth, kernel::SeamVerdict::Smooth),
|
||||
(self.curvature_jump, kernel::SeamVerdict::CurvatureJump),
|
||||
(self.sharp, kernel::SeamVerdict::Sharp),
|
||||
(self.gap, kernel::SeamVerdict::Gap),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(count, _)| *count > 0)
|
||||
.map(|(_, verdict)| verdict)
|
||||
.max()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{Session, SurfaceAnalysis};
|
||||
|
||||
fn boxed(s: &mut Session, size: f64) {
|
||||
s.execute("solid.box", &json!({"length": size, "width": size, "height": size})).unwrap();
|
||||
}
|
||||
|
||||
/// The edges of the first body of a continuity reply.
|
||||
fn edges(v: &Value) -> &Vec<Value> {
|
||||
v["bodies"][0]["edges"].as_array().unwrap_or_else(|| panic!("no edges in {v}"))
|
||||
}
|
||||
|
||||
/// The seams that read as tangent (within 0.01° of the neighbouring face).
|
||||
fn tangent(edges: &[Value]) -> Vec<&Value> {
|
||||
edges.iter().filter(|e| e["normal_angle_deg"]["value"].as_f64().unwrap_or(f64::NAN) < 0.01).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surface_analyses_are_view_state() {
|
||||
let mut s = Session::default();
|
||||
@@ -337,126 +121,4 @@ mod tests {
|
||||
assert!(s.execute("inspect.zebra", &json!({"stripes": 0})).is_err());
|
||||
assert!(s.execute("inspect.draft", &json!({"pull": [0, 0, 0]})).is_err());
|
||||
}
|
||||
|
||||
/// A box edge: the faces meet exactly (G0) and square to each other (G1), so the analysis
|
||||
/// must read 0 gap and 90°, and must keep its seams as view state without an undo step.
|
||||
#[test]
|
||||
fn continuity_reports_a_box_edge_as_a_gap_free_right_angle() {
|
||||
let mut s = Session::default();
|
||||
boxed(&mut s, 20.0);
|
||||
let undo = s.undo.len();
|
||||
let v = s.execute("inspect.continuity", &json!({})).unwrap();
|
||||
assert_eq!(edges(&v).len(), 12);
|
||||
for e in edges(&v) {
|
||||
let gap = e["gap_mm"]["value"].as_f64().unwrap();
|
||||
let angle = e["normal_angle_deg"]["value"].as_f64().unwrap();
|
||||
let jump = e["curvature_jump_per_mm"]["value"].as_f64().unwrap();
|
||||
assert!(gap < 1e-6, "gap {gap} in {e}");
|
||||
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["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}");
|
||||
let f = e["normal_angle_deg"]["edge_fraction"].as_f64().unwrap();
|
||||
assert!((0.0..=1.0).contains(&f), "{e}");
|
||||
}
|
||||
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["summary"]["edges"], json!(12));
|
||||
assert_eq!(v["summary"]["sharp"], json!(12));
|
||||
assert_eq!(v["summary"]["worst"], json!("sharp"));
|
||||
assert_eq!(s.continuity.len(), 12, "the seams are kept for the viewport");
|
||||
assert_eq!(s.undo.len(), undo, "no undo step");
|
||||
assert_eq!(s.analysis, None, "the other analyses are left alone");
|
||||
}
|
||||
|
||||
/// A rolling-ball fillet is tangent to the faces it joins but not curvature continuous: its
|
||||
/// two seams read ~0° with the fillet's 1 / radius curvature jump against the planes.
|
||||
#[test]
|
||||
fn continuity_finds_the_fillet_seams_tangent_and_their_curvature_jump() {
|
||||
let mut s = Session::default();
|
||||
boxed(&mut s, 20.0);
|
||||
s.execute("solid.fillet", &json!({"edges": [[20, 20, 10]], "radius": 4})).unwrap();
|
||||
let v = s.execute("inspect.continuity", &json!({})).unwrap();
|
||||
assert_eq!(edges(&v).len(), 15, "the rounded edge leaves three new edges behind: {v}");
|
||||
let seams = tangent(edges(&v));
|
||||
assert_eq!(seams.len(), 2, "the fillet meets its two neighbours tangentially: {v}");
|
||||
for e in seams {
|
||||
assert!(e["gap_mm"]["value"].as_f64().unwrap() < 1e-6, "{e}");
|
||||
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!(v["summary"]["curvature_jump"], json!(2));
|
||||
assert_eq!(v["summary"]["sharp"], json!(13));
|
||||
assert_eq!(v["summary"]["smooth"], json!(0));
|
||||
}
|
||||
|
||||
/// A slot's straight wall runs tangentially into its arc wall: the join is G1 but its
|
||||
/// curvature jumps by the arc's 1 / radius, which is exactly what a Class-A check looks for.
|
||||
#[test]
|
||||
fn continuity_reports_one_over_the_radius_where_a_line_meets_an_arc() {
|
||||
let mut s = Session::default();
|
||||
s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
|
||||
s.execute("sketch.slot.center_point", &json!({"center": [0, 0], "end": [20, 0], "width": 10})).unwrap();
|
||||
s.execute("solid.extrude", &json!({"distance": 5})).unwrap();
|
||||
let v = s.execute("inspect.continuity", &json!({"angle_tolerance_deg": 0.01})).unwrap();
|
||||
let seams = tangent(edges(&v));
|
||||
assert_eq!(seams.len(), 4, "a slot has four line-to-arc joins: {v}");
|
||||
for e in seams {
|
||||
assert!(e["gap_mm"]["value"].as_f64().unwrap() < 1e-6, "{e}");
|
||||
let jump = e["curvature_jump_per_mm"]["value"].as_f64().unwrap();
|
||||
assert!((jump - 0.2).abs() < 1e-6, "1 / radius 5: {e}");
|
||||
assert_eq!(e["verdict"], json!("curvature_jump"), "{e}");
|
||||
}
|
||||
assert_eq!(v["summary"]["curvature_jump"], json!(4));
|
||||
}
|
||||
|
||||
/// `clear` takes the shading away, and every continuity call stays view state.
|
||||
#[test]
|
||||
fn continuity_is_view_state_and_clears() {
|
||||
let mut s = Session::default();
|
||||
boxed(&mut s, 10.0);
|
||||
let undo = s.undo.len();
|
||||
s.execute("inspect.continuity", &json!({"samples": 5})).unwrap();
|
||||
assert_eq!(s.continuity.len(), 12);
|
||||
assert_eq!(s.undo.len(), undo, "no undo step");
|
||||
let cleared = s.execute("inspect.continuity", &json!({"clear": true})).unwrap();
|
||||
assert_eq!(cleared["cleared"], json!(true));
|
||||
assert!(s.continuity.is_empty(), "clear leaves nothing shaded");
|
||||
assert_eq!(s.undo.len(), undo);
|
||||
}
|
||||
|
||||
/// Hostile parameters are refused with an error, never a panic.
|
||||
#[test]
|
||||
fn hostile_continuity_params_are_refused() {
|
||||
let mut s = Session::default();
|
||||
boxed(&mut s, 10.0);
|
||||
for params in [
|
||||
json!({"samples": 0}),
|
||||
json!({"samples": 2}),
|
||||
json!({"samples": 258}),
|
||||
json!({"samples": 3.5}),
|
||||
json!({"samples": "33"}),
|
||||
json!({"samples": null}),
|
||||
json!({"gap_tolerance_mm": -1}),
|
||||
json!({"gap_tolerance_mm": 1e12}),
|
||||
json!({"angle_tolerance_deg": f64::NAN}),
|
||||
json!({"curvature_tolerance_per_mm": "tight"}),
|
||||
json!({"edges": 3}),
|
||||
json!({"edges": [[1, 2]]}),
|
||||
json!({"edges": [[]]}),
|
||||
json!({"edges": [{"index": 99999}]}),
|
||||
json!({"edges": [[500, 500, 500]]}),
|
||||
json!({"body": "Nope"}),
|
||||
] {
|
||||
assert!(s.execute("inspect.continuity", ¶ms).is_err(), "accepted {params}");
|
||||
}
|
||||
let many: Vec<Value> = (0..513).map(|i| json!([i as f64, 0.0, 0.0])).collect();
|
||||
assert!(s.execute("inspect.continuity", &json!({"edges": many})).is_err(), "513 picks");
|
||||
assert!(s.continuity.is_empty(), "a refused call shades nothing");
|
||||
assert_eq!(s.undo.len(), 1, "only the box is an undo step");
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,6 @@
|
||||
//! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid,
|
||||
//! selection highlights or tessellation diagonals are exported.
|
||||
|
||||
#[path = "view_dxf_meshes.rs"]
|
||||
mod meshes;
|
||||
#[path = "view_dxf_progress.rs"]
|
||||
mod progress;
|
||||
#[path = "view_dxf_projection.rs"]
|
||||
mod projection;
|
||||
|
||||
@@ -50,17 +46,28 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(path) = path {
|
||||
solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
progress::Stage::new("dxf_meshes", 1).check().map_err(|e| bad(CMD, e))?;
|
||||
let meshes = meshes::prepare(s, tolerance)?;
|
||||
let prepare_ms = started.elapsed().as_secs_f64() * 1000.;
|
||||
let drawing = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?;
|
||||
let writing = progress::Stage::new("dxf_write", 1);
|
||||
writing.check().map_err(|e| bad(CMD, e))?;
|
||||
let world = s.world_state();
|
||||
let mut meshes = Vec::new();
|
||||
let mut count = 0usize;
|
||||
for body in world.bodies.iter().filter(|b| s.body_visible(&b.name)) {
|
||||
let mesh = body.body.reference_display_mesh_angular(tolerance, solidcraft_kernel::DISPLAY_ANGLE)?;
|
||||
count = count.saturating_add(mesh.triangles.len()).saturating_add(mesh.edges.iter().map(Vec::len).sum::<usize>());
|
||||
if count > 1_000_000 {
|
||||
return Err(bad(CMD, "view too complex to export; hide bodies or increase tolerance"));
|
||||
}
|
||||
if mesh.triangles.is_empty() {
|
||||
return Err(bad(CMD, format!("{} has no exportable surface", body.name)));
|
||||
}
|
||||
meshes.push(mesh);
|
||||
}
|
||||
if meshes.is_empty() {
|
||||
return Err(bad(CMD, "no visible bodies to export"));
|
||||
}
|
||||
let lines = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?;
|
||||
let mut visible = 0;
|
||||
let mut hidden = 0;
|
||||
let mut entities = Vec::new();
|
||||
for line in drawing.lines {
|
||||
for line in lines {
|
||||
if line.hidden && !dashed {
|
||||
continue;
|
||||
}
|
||||
@@ -79,14 +86,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) });
|
||||
}
|
||||
let text = solidcraft_io::write_dxf_drawing(&layers, &entities);
|
||||
writing.check().map_err(|e| bad(CMD, e))?;
|
||||
let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}});
|
||||
result["stats"] = json!({"bodies":meshes.placements.len(),"shared_meshes":meshes.meshes.len(),"triangles":meshes.triangles,
|
||||
"mesh_bytes":meshes.bytes,"worker_limit":meshes::WORKERS,"segments":drawing.segments,"occlusion_work":drawing.work,
|
||||
"prepare_ms":prepare_ms,"projection_ms":drawing.projection_ms,"occlusion_ms":drawing.occlusion_ms});
|
||||
if let Some(path) = path {
|
||||
solidcraft_io::vfs::check(path).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
solidcraft_io::write_atomic(std::path::Path::new(path), text.as_bytes(), false).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
result["path"] = json!(path);
|
||||
} else {
|
||||
result["dxf"] = json!(text);
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
//! 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 std::collections::BTreeMap;
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use solidcraft_doc::{IDENTITY, Mat, ModelBody, mat_inverse, mat_mul};
|
||||
use solidcraft_geom::{Aabb3, Mesh, Vec3};
|
||||
use solidcraft_kernel::{KernelError, map_with_local_pools};
|
||||
|
||||
use super::{CMD, progress::Stage};
|
||||
use crate::params::bad;
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) const WORKERS: usize = 8;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) const WORKERS: usize = 1;
|
||||
const MESH_BYTES: usize = 512 * 1024 * 1024;
|
||||
const MAX_BODIES: usize = 100_000;
|
||||
|
||||
pub(super) struct Placement {
|
||||
pub mesh: usize,
|
||||
pub transform: Mat,
|
||||
pub visibility: Vec<bool>,
|
||||
}
|
||||
pub(super) struct Scene {
|
||||
pub meshes: Vec<Arc<Mesh>>,
|
||||
pub placements: Vec<Placement>,
|
||||
pub triangles: usize,
|
||||
pub bytes: usize,
|
||||
}
|
||||
|
||||
struct Group {
|
||||
first: usize,
|
||||
inverse: Mat,
|
||||
}
|
||||
struct Item<'a> {
|
||||
body: &'a ModelBody,
|
||||
group: usize,
|
||||
keep: bool,
|
||||
transform: Mat,
|
||||
}
|
||||
struct Prepared {
|
||||
mesh: Option<Arc<Mesh>>,
|
||||
visibility: Vec<bool>,
|
||||
triangles: usize,
|
||||
}
|
||||
|
||||
pub(super) fn claim(counter: &AtomicUsize, amount: usize, limit: usize) -> bool {
|
||||
let mut old = counter.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let Some(next) = old.checked_add(amount).filter(|n| *n <= limit) else { return false };
|
||||
match counter.compare_exchange_weak(old, next, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => return true,
|
||||
Err(current) => old = current,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn buffer_bytes(m: &Mesh) -> usize {
|
||||
m.positions.capacity() * size_of::<Vec3>()
|
||||
+ m.normals.capacity() * size_of::<Vec3>()
|
||||
+ m.triangles.capacity() * size_of::<[u32; 3]>()
|
||||
+ m.tri_face.capacity() * size_of::<u32>()
|
||||
+ m.edges.capacity() * size_of::<Vec<Vec3>>()
|
||||
+ m.edges.iter().map(|e| e.capacity() * size_of::<Vec3>()).sum::<usize>()
|
||||
+ m.seams.capacity()
|
||||
+ m.smooth_edges.capacity()
|
||||
+ m.sharp_edges.capacity()
|
||||
+ m.edge_faces.capacity() * size_of::<Vec<u32>>()
|
||||
+ m.edge_faces.iter().map(|e| e.capacity() * size_of::<u32>()).sum::<usize>()
|
||||
}
|
||||
|
||||
fn rigid(m: &Mat) -> bool {
|
||||
if m.iter().flatten().any(|v| !v.is_finite()) || m.iter().zip([0., 0., 0., 1.]).any(|(c, w)| (c[3] - w).abs() > 1e-10) {
|
||||
return false;
|
||||
}
|
||||
let axes = [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])];
|
||||
let [x, y, z] = axes;
|
||||
(x.len2() - 1.).abs() < 1e-9
|
||||
&& (y.len2() - 1.).abs() < 1e-9
|
||||
&& (z.len2() - 1.).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) - 1.).abs() < 1e-9
|
||||
}
|
||||
|
||||
pub(super) fn prepare(s: &Session, tolerance: f64) -> Result<Scene> {
|
||||
let world = s.world_state();
|
||||
let state = s.model.state();
|
||||
let mut definitions = BTreeMap::new();
|
||||
for body in &state.bodies {
|
||||
*definitions.entry((body.component, body.definition_name(), body.feature)).or_insert(0usize) += 1;
|
||||
}
|
||||
let mut by_definition = BTreeMap::new();
|
||||
let mut groups: Vec<Group> = Vec::new();
|
||||
let mut items = Vec::new();
|
||||
for (index, body) in world.bodies.iter().enumerate().filter(|(_, b)| s.body_visible(&b.name)) {
|
||||
if items.len() >= MAX_BODIES {
|
||||
return Err(bad(CMD, "too many placed bodies to export"));
|
||||
}
|
||||
let key = (body.component, body.definition_name(), body.feature);
|
||||
let unambiguous = definitions.get(&key) == Some(&1);
|
||||
let reused = unambiguous
|
||||
.then(|| by_definition.get(&key).copied())
|
||||
.flatten()
|
||||
.and_then(|g: usize| groups.get(g).map(|group| (g, mat_mul(&body.source_transform, &group.inverse))))
|
||||
.filter(|(_, m)| rigid(m));
|
||||
let (group, transform) = if let Some(reused) = reused {
|
||||
reused
|
||||
} else {
|
||||
let g = groups.len();
|
||||
groups.push(Group { first: index, inverse: mat_inverse(&body.source_transform).unwrap_or(IDENTITY) });
|
||||
if unambiguous && mat_inverse(&body.source_transform).is_some() {
|
||||
by_definition.entry(key).or_insert(g);
|
||||
}
|
||||
(g, IDENTITY)
|
||||
};
|
||||
let keep = groups.get(group).is_some_and(|g| g.first == index);
|
||||
items.push(Item { body, group, keep, transform });
|
||||
}
|
||||
if items.is_empty() {
|
||||
return Err(bad(CMD, "no visible bodies to export"));
|
||||
}
|
||||
let progress = Stage::new("dxf_meshes", items.len());
|
||||
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)?;
|
||||
if mesh.triangles.is_empty() {
|
||||
return Err(KernelError::Invalid(format!("{} has no exportable surface", item.body.name)));
|
||||
}
|
||||
let visibility = (0..mesh.edges.len()).map(|i| mesh.shaded_edge_visible(i)).collect();
|
||||
let triangles = mesh.triangles.len();
|
||||
let mesh = if item.keep {
|
||||
// These are owned export buffers, not the document's cached mesh. Picking and
|
||||
// shading data are unused by vector occlusion; edge choices were captured above.
|
||||
mesh.normals = Vec::new();
|
||||
mesh.tri_face = Vec::new();
|
||||
mesh.seams = Vec::new();
|
||||
mesh.smooth_edges = Vec::new();
|
||||
mesh.sharp_edges = Vec::new();
|
||||
mesh.edge_faces = Vec::new();
|
||||
if !claim(&bytes, buffer_bytes(&mesh), MESH_BYTES) {
|
||||
return Err(KernelError::Invalid("view exceeds export memory budget; hide bodies or increase tolerance".into()));
|
||||
}
|
||||
Some(Arc::new(mesh))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
progress.advance(1).map_err(|e| KernelError::Failed(e.into()))?;
|
||||
Ok(Prepared { mesh, visibility, triangles })
|
||||
});
|
||||
let mut prepared = results.into_iter().collect::<solidcraft_kernel::Result<Vec<_>>>()?;
|
||||
let mut meshes: Vec<Option<Arc<Mesh>>> = vec![None; groups.len()];
|
||||
for (item, p) in items.iter().zip(&mut prepared) {
|
||||
if let Some(mesh) = p.mesh.take()
|
||||
&& let Some(slot) = meshes.get_mut(item.group)
|
||||
{
|
||||
*slot = Some(mesh);
|
||||
}
|
||||
}
|
||||
let meshes = meshes.into_iter().map(|m| m.ok_or_else(|| bad(CMD, "missing export geometry"))).collect::<Result<Vec<_>>>()?;
|
||||
let mut placements = Vec::with_capacity(items.len());
|
||||
let mut triangles = 0usize;
|
||||
for (item, p) in items.iter().zip(prepared) {
|
||||
if meshes.get(item.group).is_none_or(|m| m.edges.len() != p.visibility.len()) {
|
||||
return Err(bad(CMD, "placed edge identity changed"));
|
||||
}
|
||||
triangles = triangles.saturating_add(p.triangles);
|
||||
placements.push(Placement { mesh: item.group, transform: item.transform, visibility: p.visibility });
|
||||
}
|
||||
Ok(Scene { meshes, placements, triangles, bytes: bytes.load(Ordering::Relaxed) })
|
||||
}
|
||||
|
||||
pub(super) fn transformed_bounds(mesh: &Mesh, m: &Mat) -> Aabb3 {
|
||||
let b = mesh.bounds();
|
||||
let mut out = Aabb3::EMPTY;
|
||||
for x in [b.min.x, b.max.x] {
|
||||
for y in [b.min.y, b.max.y] {
|
||||
for z in [b.min.z, b.max.z] {
|
||||
out.add(solidcraft_doc::apply_point(m, Vec3::new(x, y, z)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_proper_rigid_placements_share_geometry() {
|
||||
assert!(rigid(&solidcraft_doc::rigid(Vec3::new(1., 2., 3.), Vec3::ZERO, Vec3::Z, 0.7)));
|
||||
let mut m = IDENTITY;
|
||||
m[0][0] = -1.;
|
||||
assert!(!rigid(&m));
|
||||
m[0][0] = 2.;
|
||||
assert!(!rigid(&m));
|
||||
m[0][0] = f64::NAN;
|
||||
assert!(!rigid(&m));
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
//! Stage counters shared by the export worker and its bounded computation workers.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub(super) const CANCELLED: &str = "DXF export cancelled";
|
||||
|
||||
pub(super) struct Stage {
|
||||
watch: Option<Arc<dyn solidcraft_kernel::watch::Watch>>,
|
||||
name: &'static str,
|
||||
total: usize,
|
||||
done: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub fn new(name: &'static str, total: usize) -> Self {
|
||||
let stage = Self { watch: solidcraft_kernel::watch::current(), name, total: total.max(1), done: Mutex::new(0) };
|
||||
if let Some(watch) = &stage.watch {
|
||||
watch.progress(name, 0, stage.total);
|
||||
}
|
||||
stage
|
||||
}
|
||||
pub fn check(&self) -> Result<(), &'static str> {
|
||||
if self.watch.as_ref().is_some_and(|w| w.cancelled()) { Err(CANCELLED) } else { Ok(()) }
|
||||
}
|
||||
pub fn advance(&self, count: usize) -> Result<(), &'static str> {
|
||||
self.check()?;
|
||||
if let Some(watch) = &self.watch {
|
||||
// Serialize reports as well as increments: eight workers must not report a
|
||||
// smaller completed count after a larger one.
|
||||
let mut done = self.done.lock().map_err(|_| "export progress unavailable")?;
|
||||
*done = done.saturating_add(count).min(self.total);
|
||||
watch.progress(self.name, *done, self.total);
|
||||
}
|
||||
self.check()
|
||||
}
|
||||
}
|
||||
@@ -1,27 +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.
|
||||
#[cfg(test)]
|
||||
use solidcraft_geom::Mesh;
|
||||
use solidcraft_geom::{Aabb3, Vec2, Vec3};
|
||||
use solidcraft_geom::{Aabb3, Mesh, Vec2, Vec3};
|
||||
use solidcraft_io::{DxfEntity, DxfShape};
|
||||
use solidcraft_render::Camera;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[path = "view_dxf_scene.rs"]
|
||||
mod scene;
|
||||
|
||||
pub(super) struct Drawing {
|
||||
pub lines: Vec<Line>,
|
||||
pub work: usize,
|
||||
pub segments: usize,
|
||||
pub projection_ms: f64,
|
||||
pub occlusion_ms: f64,
|
||||
}
|
||||
|
||||
pub(super) fn drawing(meshes: &super::meshes::Scene, cam: &Camera) -> Result<Drawing, &'static str> {
|
||||
scene::drawing(meshes, cam)
|
||||
}
|
||||
|
||||
/// Keep the hidden curves connected: restarting a dash on every short chord would make a
|
||||
/// small circular hole look solid. Degree-two joins continue; junctions end the polyline.
|
||||
pub(super) fn connect(entities: Vec<DxfEntity>) -> Vec<DxfEntity> {
|
||||
@@ -67,7 +50,6 @@ pub(super) fn connect(entities: Vec<DxfEntity>) -> Vec<DxfEntity> {
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Line {
|
||||
pub a: Vec2,
|
||||
pub b: Vec2,
|
||||
@@ -91,18 +73,15 @@ fn overlap(a: &Aabb3, b: &Aabb3) -> bool {
|
||||
a.min.x <= b.max.x && b.min.x <= a.max.x && a.min.y <= b.max.y && b.min.y <= a.max.y
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
struct Triangle {
|
||||
p: [Vec3; 3],
|
||||
bounds: Aabb3,
|
||||
}
|
||||
#[cfg(test)]
|
||||
struct Tree {
|
||||
bounds: Aabb3,
|
||||
children: Option<(Box<Tree>, Box<Tree>)>,
|
||||
triangles: Vec<Triangle>,
|
||||
}
|
||||
#[cfg(test)]
|
||||
impl Tree {
|
||||
fn new(mut triangles: Vec<Triangle>) -> Self {
|
||||
let b = triangles.iter().fold(Aabb3::EMPTY, |b, t| b.union(&t.bounds));
|
||||
@@ -234,7 +213,6 @@ fn merge_lines(lines: Vec<Line>, eps: f64) -> Vec<Line> {
|
||||
|
||||
/// B-rep edges plus curved silhouettes. Triangle adjacency is welded by position because
|
||||
/// different faces can have different vertex indices along their shared boundary.
|
||||
#[cfg(test)]
|
||||
fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> {
|
||||
let mut result = Vec::new();
|
||||
for (_, e) in mesh.edges.iter().enumerate().filter(|(i, _)| mesh.shaded_edge_visible(*i)) {
|
||||
@@ -263,8 +241,7 @@ fn edges(mesh: &Mesh, cam: &Camera, eps: f64) -> Vec<(Vec3, Vec3)> {
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn reference_drawing(meshes: &[Mesh], cam: &Camera) -> Result<Vec<Line>, &'static str> {
|
||||
pub(super) fn drawing(meshes: &[Mesh], cam: &Camera) -> Result<Vec<Line>, &'static str> {
|
||||
let (right, up, back) = cam.basis();
|
||||
let scale = meshes.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bounds())).diagonal().max(1.0);
|
||||
let eps = scale * 1e-8;
|
||||
|
||||
@@ -1,627 +0,0 @@
|
||||
//! Two levels of occlusion acceleration: an instance tree over projected bounds, and one
|
||||
//! 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 std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use solidcraft_doc::apply_point;
|
||||
use solidcraft_geom::{Aabb3, Mesh, Vec3};
|
||||
use solidcraft_render::Camera;
|
||||
|
||||
use super::super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds};
|
||||
use super::super::progress::Stage;
|
||||
use super::{Drawing, Line, bounds, clip, key, merge_lines, occluded, overlap, xy};
|
||||
|
||||
const TOO_COMPLEX: &str = "view exceeds export work budget; hide bodies or increase tolerance";
|
||||
const MAX_LINES: usize = 1_000_000;
|
||||
const MAX_SEGMENTS: usize = 4_000_000;
|
||||
const MAX_SHARED_TRIANGLES: usize = 2_000_000;
|
||||
const MAX_VIEW_NODES: usize = 256 * 1024 * 1024 / std::mem::size_of::<Aabb3>();
|
||||
const WORK: usize = 200_000_000;
|
||||
|
||||
fn parallel<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> Result<R, &'static str> + Sync) -> Result<Vec<R>, &'static str> {
|
||||
solidcraft_kernel::map_on_threads(items, WORKERS, f).into_iter().map(|r| r.ok_or("export worker failed")?).collect()
|
||||
}
|
||||
|
||||
struct Node {
|
||||
bounds: Aabb3,
|
||||
start: usize,
|
||||
end: usize,
|
||||
children: Option<(usize, usize)>,
|
||||
}
|
||||
struct Bvh {
|
||||
nodes: Vec<Node>,
|
||||
ids: Vec<usize>,
|
||||
}
|
||||
impl Bvh {
|
||||
fn new(boxes: &[Aabb3], flat: bool) -> Self {
|
||||
let mut tree = Self { nodes: Vec::new(), ids: (0..boxes.len()).collect() };
|
||||
if !boxes.is_empty() {
|
||||
tree.build(boxes, 0, boxes.len(), flat);
|
||||
}
|
||||
tree
|
||||
}
|
||||
fn build(&mut self, boxes: &[Aabb3], start: usize, end: usize, flat: bool) -> usize {
|
||||
let b = self.ids.get(start..end).into_iter().flatten().filter_map(|i| boxes.get(*i)).fold(Aabb3::EMPTY, |b, t| b.union(t));
|
||||
let index = self.nodes.len();
|
||||
self.nodes.push(Node { bounds: b, start, end, children: None });
|
||||
if end - start > 8 {
|
||||
let size = b.size();
|
||||
let axis = if !flat && size.z > size.x.max(size.y) {
|
||||
2
|
||||
} else if size.x > size.y {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let value = |i: &usize| {
|
||||
boxes.get(*i).map(|b| b.center()).map_or(0., |p| match axis {
|
||||
0 => p.x,
|
||||
1 => p.y,
|
||||
_ => p.z,
|
||||
})
|
||||
};
|
||||
let mid = start + (end - start) / 2;
|
||||
if let Some(ids) = self.ids.get_mut(start..end) {
|
||||
ids.select_nth_unstable_by(mid - start, |a, b| value(a).total_cmp(&value(b)).then_with(|| a.cmp(b)));
|
||||
}
|
||||
let left = self.build(boxes, start, mid, flat);
|
||||
let right = self.build(boxes, mid, end, flat);
|
||||
if let Some(node) = self.nodes.get_mut(index) {
|
||||
node.children = Some((left, right));
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
}
|
||||
|
||||
struct Edge {
|
||||
vertices: [u32; 2],
|
||||
start: usize,
|
||||
end: usize,
|
||||
}
|
||||
struct Side {
|
||||
key: [[i64; 3]; 2],
|
||||
vertices: [u32; 2],
|
||||
triangle: usize,
|
||||
}
|
||||
struct Shared {
|
||||
mesh: Arc<Mesh>,
|
||||
tree: Bvh,
|
||||
edges: Vec<Edge>,
|
||||
incident: Vec<usize>,
|
||||
}
|
||||
impl Shared {
|
||||
fn new(mesh: &Arc<Mesh>, eps: f64, progress: &Stage) -> Result<Self, &'static str> {
|
||||
let mut boxes = Vec::with_capacity(mesh.triangles.len());
|
||||
let mut sides = Vec::new();
|
||||
for (i, indices) in mesh.triangles.iter().enumerate() {
|
||||
if i.is_multiple_of(1024) {
|
||||
progress.check()?;
|
||||
}
|
||||
let points = mesh.tri(indices).ok_or("invalid export triangle")?;
|
||||
if points.iter().any(|p| !p.is_finite()) {
|
||||
return Err("model contains invalid coordinates");
|
||||
}
|
||||
boxes.push(bounds(points));
|
||||
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
|
||||
let (Some(pa), Some(pb), Some(ia), Some(ib)) = (points.get(a), points.get(b), indices.get(a), indices.get(b)) else {
|
||||
return Err("invalid export edge");
|
||||
};
|
||||
let (ka, kb) = (key(*pa, eps), key(*pb, eps));
|
||||
if ka == kb {
|
||||
continue;
|
||||
}
|
||||
let (key, vertices) = if ka < kb { ([ka, kb], [*ia, *ib]) } else { ([kb, ka], [*ib, *ia]) };
|
||||
sides.push(Side { key, vertices, triangle: i });
|
||||
}
|
||||
}
|
||||
let tree = Bvh::new(&boxes, false);
|
||||
sides.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.triangle.cmp(&b.triangle)));
|
||||
let mut edges: Vec<Edge> = Vec::new();
|
||||
let mut incident = Vec::with_capacity(sides.len());
|
||||
let mut previous = None;
|
||||
for side in sides {
|
||||
if previous != Some(side.key) {
|
||||
edges.push(Edge { vertices: side.vertices, start: incident.len(), end: incident.len() });
|
||||
previous = Some(side.key);
|
||||
}
|
||||
incident.push(side.triangle);
|
||||
if let Some(e) = edges.last_mut() {
|
||||
e.end = incident.len();
|
||||
}
|
||||
}
|
||||
Ok(Self { mesh: mesh.clone(), tree, edges, incident })
|
||||
}
|
||||
}
|
||||
|
||||
struct View<'a> {
|
||||
cam: &'a Camera,
|
||||
right: Vec3,
|
||||
up: Vec3,
|
||||
back: Vec3,
|
||||
}
|
||||
impl<'a> View<'a> {
|
||||
fn new(cam: &'a Camera) -> Self {
|
||||
let (right, up, back) = cam.basis();
|
||||
Self { cam, right, up, back }
|
||||
}
|
||||
fn project(&self, p: Vec3) -> Result<Vec3, &'static str> {
|
||||
if !p.is_finite() {
|
||||
return Err("model contains invalid coordinates");
|
||||
}
|
||||
let d = p - self.cam.target;
|
||||
let z = d.dot(self.back);
|
||||
let projected = if self.cam.fov > 0. {
|
||||
let w = self.cam.distance - z;
|
||||
if w <= self.cam.distance * 1e-6 {
|
||||
return Err("model crosses the camera eye plane; zoom out before exporting");
|
||||
}
|
||||
Vec3::new(d.dot(self.right) * self.cam.distance / w, d.dot(self.up) * self.cam.distance / w, 1. / w)
|
||||
} else {
|
||||
Vec3::new(d.dot(self.right), d.dot(self.up), z)
|
||||
};
|
||||
if !projected.is_finite() || projected.len() > 1e12 {
|
||||
return Err("projected coordinates exceed the export range");
|
||||
}
|
||||
Ok(projected)
|
||||
}
|
||||
fn triangle(&self, shared: &Shared, placed: &Placement, id: usize) -> Result<[Vec3; 3], &'static str> {
|
||||
let indices = shared.mesh.triangles.get(id).ok_or("invalid export triangle")?;
|
||||
let [a, b, c] = shared.mesh.tri(indices).ok_or("invalid export triangle")?;
|
||||
Ok([
|
||||
self.project(apply_point(&placed.transform, a))?,
|
||||
self.project(apply_point(&placed.transform, b))?,
|
||||
self.project(apply_point(&placed.transform, c))?,
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
struct Projected {
|
||||
nodes: Vec<Aabb3>,
|
||||
segments: Vec<(Vec3, Vec3)>,
|
||||
}
|
||||
impl Projected {
|
||||
fn new(shared: &Shared, placed: &Placement, view: &View<'_>, eps: f64, segments: &AtomicUsize, progress: &Stage) -> Result<Self, &'static str> {
|
||||
let mut nodes = vec![Aabb3::EMPTY; shared.tree.nodes.len()];
|
||||
// Exact projected leaf bounds avoid false near-eye errors from empty corners of a
|
||||
// rotated model-space box. Interior bounds are just unions of the child bounds.
|
||||
let mut front = vec![false; shared.mesh.triangles.len()];
|
||||
for (i, node) in shared.tree.nodes.iter().enumerate().rev() {
|
||||
if i.is_multiple_of(1024) {
|
||||
progress.check()?;
|
||||
}
|
||||
let mut b = Aabb3::EMPTY;
|
||||
if let Some((left, right)) = node.children {
|
||||
b = nodes.get(left).ok_or("invalid export tree")?.union(nodes.get(right).ok_or("invalid export tree")?);
|
||||
} else {
|
||||
for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid export tree")? {
|
||||
let p = view.triangle(shared, placed, *id)?;
|
||||
b = b.union(&bounds(p));
|
||||
if let Some(f) = front.get_mut(*id) {
|
||||
// A positive projective scale preserves the projected winding.
|
||||
*f = super::cross(xy(p[1] - p[0]), xy(p[2] - p[0])) > 0.;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(slot) = nodes.get_mut(i) {
|
||||
*slot = b;
|
||||
}
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
let mut add = |a: Vec3, b: Vec3| -> Result<(), &'static str> {
|
||||
let (a, b) = (view.project(apply_point(&placed.transform, a))?, view.project(apply_point(&placed.transform, b))?);
|
||||
if xy(a).dist(xy(b)) > eps {
|
||||
if !claim(segments, 1, MAX_SEGMENTS) {
|
||||
return Err(TOO_COMPLEX);
|
||||
}
|
||||
result.push((a, b));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for (i, edge) in shared.mesh.edges.iter().enumerate() {
|
||||
if !placed.visibility.get(i).copied().unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
for w in edge.windows(2) {
|
||||
if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
|
||||
add(*a, *b)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for edge in &shared.edges {
|
||||
let mut positive = false;
|
||||
let mut negative = false;
|
||||
for id in shared.incident.get(edge.start..edge.end).ok_or("invalid export adjacency")? {
|
||||
if front.get(*id).copied().ok_or("invalid export adjacency")? {
|
||||
positive = true;
|
||||
} else {
|
||||
negative = true;
|
||||
}
|
||||
}
|
||||
if (positive && negative) || edge.end - edge.start == 1 {
|
||||
let a = shared.mesh.positions.get(edge.vertices[0] as usize).ok_or("invalid silhouette")?;
|
||||
let b = shared.mesh.positions.get(edge.vertices[1] as usize).ok_or("invalid silhouette")?;
|
||||
add(*a, *b)?;
|
||||
}
|
||||
}
|
||||
Ok(Self { nodes, segments: result })
|
||||
}
|
||||
}
|
||||
|
||||
/// A sorted union, updated as occluders are found. A node's line interval already covered by
|
||||
/// nearer triangles cannot change the result and is skipped before visiting its children.
|
||||
#[derive(Default)]
|
||||
struct Coverage {
|
||||
spans: Vec<(f64, f64)>,
|
||||
}
|
||||
impl Coverage {
|
||||
fn contains(&self, lo: f64, hi: f64) -> bool {
|
||||
self.spans.iter().any(|(a, b)| *a <= lo && *b >= hi)
|
||||
}
|
||||
fn add(&mut self, mut lo: f64, mut hi: f64) -> Result<(), &'static str> {
|
||||
let first = self.spans.partition_point(|(_, b)| *b + 1e-9 < lo);
|
||||
let mut end = first;
|
||||
while let Some((a, b)) = self.spans.get(end) {
|
||||
if *a > hi + 1e-9 {
|
||||
break;
|
||||
}
|
||||
lo = lo.min(*a);
|
||||
hi = hi.max(*b);
|
||||
end += 1;
|
||||
}
|
||||
if first == end && self.spans.len() >= MAX_LINES / 2 {
|
||||
return Err(TOO_COMPLEX);
|
||||
}
|
||||
self.spans.splice(first..end, [(lo, hi)]);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn rectangle(a: Vec3, b: Vec3, box_: &Aabb3) -> Option<(f64, f64)> {
|
||||
let (mut lo, mut hi) = (0., 1.);
|
||||
for (v0, v1) in [
|
||||
(a.x - box_.min.x, b.x - box_.min.x),
|
||||
(box_.max.x - a.x, box_.max.x - b.x),
|
||||
(a.y - box_.min.y, b.y - box_.min.y),
|
||||
(box_.max.y - a.y, box_.max.y - b.y),
|
||||
] {
|
||||
if !clip(&mut lo, &mut hi, v0, v1) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some((lo, hi))
|
||||
}
|
||||
|
||||
struct Budget<'a> {
|
||||
global: &'a AtomicUsize,
|
||||
progress: &'a Stage,
|
||||
local: usize,
|
||||
spent: usize,
|
||||
}
|
||||
impl<'a> Budget<'a> {
|
||||
fn new(global: &'a AtomicUsize, progress: &'a Stage) -> Self {
|
||||
Self { global, progress, local: 0, spent: 0 }
|
||||
}
|
||||
fn spend(&mut self) -> Result<(), &'static str> {
|
||||
if self.local == 0 {
|
||||
self.progress.check()?;
|
||||
let mut old = self.global.load(Ordering::Relaxed);
|
||||
loop {
|
||||
let granted = old.min(4096);
|
||||
if granted == 0 {
|
||||
return Err(TOO_COMPLEX);
|
||||
}
|
||||
match self.global.compare_exchange_weak(old, old - granted, Ordering::Relaxed, Ordering::Relaxed) {
|
||||
Ok(_) => {
|
||||
self.local = granted;
|
||||
break;
|
||||
}
|
||||
Err(current) => old = current,
|
||||
}
|
||||
}
|
||||
}
|
||||
self.local -= 1;
|
||||
self.spent += 1;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Query<'a, 'b> {
|
||||
shared: &'a [Shared],
|
||||
scene: &'a Scene,
|
||||
projected: &'a [Projected],
|
||||
instances: &'a Bvh,
|
||||
view: &'a View<'a>,
|
||||
depth_eps: f64,
|
||||
a: Vec3,
|
||||
b: Vec3,
|
||||
bounds: Aabb3,
|
||||
covered: Coverage,
|
||||
budget: &'b mut Budget<'a>,
|
||||
}
|
||||
impl Query<'_, '_> {
|
||||
fn relevant(&self, b: &Aabb3) -> bool {
|
||||
if b.max.z <= self.a.z.min(self.b.z) + self.depth_eps || !overlap(b, &self.bounds) {
|
||||
return false;
|
||||
}
|
||||
rectangle(self.a, self.b, b).is_some_and(|(lo, hi)| !self.covered.contains(lo, hi))
|
||||
}
|
||||
fn instance_node(&mut self, index: usize) -> Result<(), &'static str> {
|
||||
self.budget.spend()?;
|
||||
let node = self.instances.nodes.get(index).ok_or("invalid instance tree")?;
|
||||
if !self.relevant(&node.bounds) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((left, right)) = node.children {
|
||||
let depth = |i: usize| self.instances.nodes.get(i).map_or(f64::NEG_INFINITY, |n| n.bounds.max.z);
|
||||
let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) };
|
||||
self.instance_node(near)?;
|
||||
if !self.covered.contains(0., 1.) {
|
||||
self.instance_node(far)?;
|
||||
}
|
||||
} else {
|
||||
for id in self.instances.ids.get(node.start..node.end).ok_or("invalid instance tree")? {
|
||||
self.mesh_node(*id, 0)?;
|
||||
if self.covered.contains(0., 1.) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn mesh_node(&mut self, instance: usize, index: usize) -> Result<(), &'static str> {
|
||||
self.budget.spend()?;
|
||||
let placed = self.scene.placements.get(instance).ok_or("invalid instance")?;
|
||||
let shared = self.shared.get(placed.mesh).ok_or("invalid shared geometry")?;
|
||||
let projected = self.projected.get(instance).ok_or("invalid instance bounds")?;
|
||||
let b = projected.nodes.get(index).ok_or("invalid mesh tree")?;
|
||||
if !self.relevant(b) {
|
||||
return Ok(());
|
||||
}
|
||||
let node = shared.tree.nodes.get(index).ok_or("invalid mesh tree")?;
|
||||
if let Some((left, right)) = node.children {
|
||||
let depth = |i: usize| projected.nodes.get(i).map_or(f64::NEG_INFINITY, |b| b.max.z);
|
||||
let (near, far) = if depth(left) >= depth(right) { (left, right) } else { (right, left) };
|
||||
self.mesh_node(instance, near)?;
|
||||
if !self.covered.contains(0., 1.) {
|
||||
self.mesh_node(instance, far)?;
|
||||
}
|
||||
} else {
|
||||
for id in shared.tree.ids.get(node.start..node.end).ok_or("invalid mesh tree")? {
|
||||
self.budget.spend()?;
|
||||
let points = self.view.triangle(shared, placed, *id)?;
|
||||
if let Some((lo, hi)) = occluded(self.a, self.b, points, self.depth_eps) {
|
||||
self.covered.add(lo, hi)?;
|
||||
if self.covered.contains(0., 1.) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result<Drawing, &'static str> {
|
||||
let start = Instant::now();
|
||||
let scale = scene
|
||||
.placements
|
||||
.iter()
|
||||
.filter_map(|p| scene.meshes.get(p.mesh).map(|m| transformed_bounds(m, &p.transform)))
|
||||
.fold(Aabb3::EMPTY, |b, p| b.union(&p))
|
||||
.diagonal()
|
||||
.max(1.);
|
||||
if !scale.is_finite() {
|
||||
return Err("model contains invalid coordinates");
|
||||
}
|
||||
let eps = scale * 1e-8;
|
||||
// Indexed input can have many triangles but very few positions. Bound adjacency/sort
|
||||
// scratch space as well as the retained mesh bytes before starting parallel builders.
|
||||
let unique_triangles = scene.meshes.iter().try_fold(0usize, |n, m| n.checked_add(m.triangles.len()));
|
||||
if unique_triangles.is_none_or(|n| n > MAX_SHARED_TRIANGLES) {
|
||||
return Err("view exceeds export memory budget; hide bodies or increase tolerance");
|
||||
}
|
||||
let progress = Stage::new("dxf_index", scene.meshes.len());
|
||||
let shared = parallel(&scene.meshes, |m| {
|
||||
progress.check()?;
|
||||
let shared = Shared::new(m, eps, &progress)?;
|
||||
progress.advance(1)?;
|
||||
Ok(shared)
|
||||
})?;
|
||||
let count = scene.placements.iter().try_fold(0usize, |n, p| n.checked_add(shared.get(p.mesh)?.tree.nodes.len()));
|
||||
if count.is_none_or(|n| n > MAX_VIEW_NODES) {
|
||||
return Err("view exceeds export memory budget; hide bodies or increase tolerance");
|
||||
}
|
||||
let view = View::new(cam);
|
||||
let count = AtomicUsize::new(0);
|
||||
let progress = Stage::new("dxf_projection", scene.placements.len());
|
||||
let projected = parallel(&scene.placements, |p| {
|
||||
progress.check()?;
|
||||
let projected = Projected::new(shared.get(p.mesh).ok_or("missing shared geometry")?, p, &view, eps, &count, &progress)?;
|
||||
progress.advance(1)?;
|
||||
Ok(projected)
|
||||
})?;
|
||||
let boxes = projected.iter().map(|p| p.nodes.first().copied().unwrap_or(Aabb3::EMPTY)).collect::<Vec<_>>();
|
||||
let mut instances = Bvh::new(&boxes, true);
|
||||
// The view is fixed for the entire drawing. Sort the at-most-eight members of each
|
||||
// instance leaf once, rather than allocating/sorting on every line query.
|
||||
for node in instances.nodes.iter().filter(|n| n.children.is_none()) {
|
||||
if let Some(ids) = instances.ids.get_mut(node.start..node.end) {
|
||||
ids.sort_unstable_by(|a, b| {
|
||||
boxes
|
||||
.get(*b)
|
||||
.map_or(f64::NEG_INFINITY, |b| b.max.z)
|
||||
.total_cmp(&boxes.get(*a).map_or(f64::NEG_INFINITY, |b| b.max.z))
|
||||
.then_with(|| a.cmp(b))
|
||||
});
|
||||
}
|
||||
}
|
||||
let segment_count = count.load(Ordering::Relaxed);
|
||||
let projection_ms = start.elapsed().as_secs_f64() * 1000.;
|
||||
let start = Instant::now();
|
||||
let depth_eps = if cam.fov > 0. { 1e-8 / cam.distance } else { eps };
|
||||
let global = AtomicUsize::new(WORK);
|
||||
let output = AtomicUsize::new(0);
|
||||
let chunks = projected.iter().flat_map(|p| p.segments.chunks(128)).collect::<Vec<_>>();
|
||||
let progress = Stage::new("dxf_occlusion", segment_count);
|
||||
let results = parallel(&chunks, |chunk| {
|
||||
progress.check()?;
|
||||
let mut budget = Budget::new(&global, &progress);
|
||||
let mut lines = Vec::new();
|
||||
for &(a, b) in *chunk {
|
||||
let mut query = Query {
|
||||
shared: &shared,
|
||||
scene,
|
||||
projected: &projected,
|
||||
instances: &instances,
|
||||
view: &view,
|
||||
depth_eps,
|
||||
a,
|
||||
b,
|
||||
bounds: bounds([a, b]),
|
||||
covered: Coverage::default(),
|
||||
budget: &mut budget,
|
||||
};
|
||||
query.instance_node(0)?;
|
||||
let mut cursor = 0.;
|
||||
let mut emit = |lo: f64, hi: f64, hidden: bool| -> Result<(), &'static str> {
|
||||
let (p, q) = (xy(a + (b - a) * lo), xy(a + (b - a) * hi));
|
||||
if p.dist(q) > eps {
|
||||
if !claim(&output, 1, MAX_LINES) {
|
||||
return Err(TOO_COMPLEX);
|
||||
}
|
||||
lines.push(Line { a: p, b: q, hidden });
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for (lo, hi) in query.covered.spans {
|
||||
emit(cursor, lo, false)?;
|
||||
emit(lo, hi, true)?;
|
||||
cursor = hi;
|
||||
}
|
||||
emit(cursor, 1., false)?;
|
||||
}
|
||||
progress.advance(chunk.len())?;
|
||||
Ok((lines, budget.spent))
|
||||
})?;
|
||||
let work = results.iter().map(|(_, n)| *n).sum();
|
||||
let lines = merge_lines(results.into_iter().flat_map(|(lines, _)| lines).collect(), eps);
|
||||
progress.check()?;
|
||||
Ok(Drawing { lines, work, segments: segment_count, projection_ms, occlusion_ms: start.elapsed().as_secs_f64() * 1000. })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn coverage_handles_disjoint_spans_and_early_complete_coverage() {
|
||||
let mut c = Coverage::default();
|
||||
c.add(0.4, 0.6).unwrap();
|
||||
c.add(0., 0.2).unwrap();
|
||||
assert!(c.contains(0.05, 0.15));
|
||||
assert!(!c.contains(0., 1.));
|
||||
c.add(0.2, 0.9).unwrap();
|
||||
c.add(0.8, 1.).unwrap();
|
||||
assert_eq!(c.spans, vec![(0., 1.)]);
|
||||
}
|
||||
|
||||
fn box_mesh() -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
mesh.positions = vec![
|
||||
Vec3::new(0., 0., 0.),
|
||||
Vec3::new(8., 0., 0.),
|
||||
Vec3::new(8., 6., 0.),
|
||||
Vec3::new(0., 6., 0.),
|
||||
Vec3::new(0., 0., 3.),
|
||||
Vec3::new(8., 0., 3.),
|
||||
Vec3::new(8., 6., 3.),
|
||||
Vec3::new(0., 6., 3.),
|
||||
];
|
||||
mesh.triangles =
|
||||
vec![[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [1, 2, 6], [1, 6, 5], [2, 3, 7], [2, 7, 6], [3, 0, 4], [3, 4, 7]];
|
||||
mesh.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)]
|
||||
.into_iter()
|
||||
.map(|(a, b)| vec![mesh.positions[a], mesh.positions[b]])
|
||||
.collect();
|
||||
mesh
|
||||
}
|
||||
|
||||
fn canonical(lines: Vec<Line>) -> 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 mut result = lines
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let (a, b) = (k(l.a), k(l.b));
|
||||
if a < b { (a, b, l.hidden) } else { (b, a, l.hidden) }
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
result.sort_unstable();
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_rotated_instances_match_flat_occlusion_in_orthographic_and_perspective_views() {
|
||||
use std::sync::Arc;
|
||||
let mesh = box_mesh();
|
||||
let mut placements = Vec::new();
|
||||
let mut flat = Vec::new();
|
||||
for (offset, angle) in [(Vec3::ZERO, 0.), (Vec3::new(3., 2., 4.), 0.3), (Vec3::new(2., 1., -4.), -0.6)] {
|
||||
let transform = solidcraft_doc::rigid(offset, Vec3::ZERO, Vec3::Z, angle);
|
||||
placements.push(Placement { mesh: 0, transform, visibility: vec![true; mesh.edges.len()] });
|
||||
let mut placed = mesh.clone();
|
||||
placed.positions = placed.positions.iter().map(|p| apply_point(&transform, *p)).collect();
|
||||
placed.edges = placed.edges.iter().map(|e| e.iter().map(|p| apply_point(&transform, *p)).collect()).collect();
|
||||
flat.push(placed);
|
||||
}
|
||||
let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 36, bytes: 0 };
|
||||
for (yaw, pitch, roll) in [(0., std::f64::consts::FRAC_PI_2, 0.), (0.7, 0.4, 0.2), (0., 0., 0.)] {
|
||||
for fov in [0., 0.6] {
|
||||
let cam = Camera { target: Vec3::new(4., 3., 1.), yaw, pitch, roll, fov, distance: 100., ..Default::default() };
|
||||
let expected = super::super::reference_drawing(&flat, &cam).unwrap();
|
||||
let actual = drawing(&scene, &cam).unwrap();
|
||||
assert_eq!(canonical(actual.lines), canonical(expected), "yaw={yaw}, pitch={pitch}, fov={fov}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_surface_over_one_million_triangles_keeps_one_mesh_and_exports_all_placements() {
|
||||
use solidcraft_render::StandardView;
|
||||
use std::sync::Arc;
|
||||
let mut mesh = Mesh::default();
|
||||
for y in 0..=100 {
|
||||
for x in 0..=100 {
|
||||
mesh.positions.push(Vec3::new(x as f64 / 10., y as f64 / 10., 0.));
|
||||
}
|
||||
}
|
||||
for y in 0..100u32 {
|
||||
for x in 0..100u32 {
|
||||
let a = y * 101 + x;
|
||||
mesh.triangles.extend([[a, a + 1, a + 102], [a, a + 102, a + 101]]);
|
||||
}
|
||||
}
|
||||
mesh.edges = vec![
|
||||
vec![Vec3::ZERO, Vec3::new(10., 0., 0.)],
|
||||
vec![Vec3::new(10., 0., 0.), Vec3::new(10., 10., 0.)],
|
||||
vec![Vec3::new(10., 10., 0.), Vec3::new(0., 10., 0.)],
|
||||
vec![Vec3::new(0., 10., 0.), Vec3::ZERO],
|
||||
];
|
||||
let placements = (0..60)
|
||||
.map(|i| Placement {
|
||||
mesh: 0,
|
||||
transform: solidcraft_doc::rigid(Vec3::new((i % 10) as f64 * 20., (i / 10) as f64 * 20., 0.), Vec3::ZERO, Vec3::Z, 0.),
|
||||
visibility: vec![true; 4],
|
||||
})
|
||||
.collect();
|
||||
let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 1_200_000, bytes: 0 };
|
||||
let mut cam = Camera { target: Vec3::new(95., 55., 0.), fov: 0., distance: 300., ..Default::default() };
|
||||
cam.set_view(StandardView::Top);
|
||||
let result = drawing(&scene, &cam).unwrap();
|
||||
assert_eq!(scene.meshes.len(), 1);
|
||||
assert_eq!(result.lines.len(), 240);
|
||||
assert!(result.lines.iter().all(|l| !l.hidden));
|
||||
}
|
||||
}
|
||||
@@ -21,49 +21,6 @@ fn export(s: &mut Session, c: Camera, hidden: &str) -> Value {
|
||||
run(s, CMD, json!({"camera":c,"hidden":hidden}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_dxf_cancellation_at_each_stage_preserves_the_destination_and_document() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
struct CancelAt {
|
||||
stage: &'static str,
|
||||
cancelled: AtomicBool,
|
||||
reached: AtomicBool,
|
||||
}
|
||||
impl solidcraft_kernel::watch::Watch for CancelAt {
|
||||
fn cancelled(&self) -> bool {
|
||||
self.cancelled.load(Ordering::Relaxed)
|
||||
}
|
||||
fn progress(&self, stage: &'static str, done: usize, _total: usize) {
|
||||
if stage == self.stage && (done > 0 || stage == "dxf_write") {
|
||||
self.reached.store(true, Ordering::Relaxed);
|
||||
self.cancelled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-dxf-cancel-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("drawing.dxf");
|
||||
let mut s = sample();
|
||||
let doc = s.doc.clone();
|
||||
let undo = s.undo.len();
|
||||
for stage in ["dxf_meshes", "dxf_index", "dxf_projection", "dxf_occlusion", "dxf_write"] {
|
||||
std::fs::write(&path, b"previous drawing").unwrap();
|
||||
let watch = Arc::new(CancelAt { stage, cancelled: AtomicBool::new(false), reached: AtomicBool::new(false) });
|
||||
let result = solidcraft_kernel::watch::watching(watch.clone(), || {
|
||||
s.execute(CMD, &json!({"camera":camera(StandardView::Top),"path":path.to_string_lossy()}))
|
||||
});
|
||||
assert!(result.unwrap_err().to_string().contains("cancelled"), "{stage}");
|
||||
assert!(watch.reached.load(Ordering::Relaxed), "{stage}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"previous drawing", "{stage}");
|
||||
assert!(Arc::ptr_eq(&doc, &s.doc));
|
||||
assert_eq!(s.undo.len(), undo);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_dxf_blind_back_hole_is_omitted_or_dashed_and_front_hole_is_visible() {
|
||||
let mut s = sample();
|
||||
@@ -143,32 +100,3 @@ fn view_dxf_rejects_invalid_options_and_near_eye_geometry_without_panicking() {
|
||||
c.fov = 4.;
|
||||
assert!(s.execute(CMD, &json!({"camera":c})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_dxf_keeps_every_occurrence_while_sharing_geometry() {
|
||||
let mut s = Session::default();
|
||||
let component = run(&mut s, "component.create", json!({"name":"Repeated part"}))["component"].as_u64().unwrap();
|
||||
run(&mut s, "solid.box", json!({"length":8,"width":6,"height":3}));
|
||||
for x in [15., 30.] {
|
||||
run(&mut s, "occurrence.copy", json!({"component":component,"translate":[x,0,0]}));
|
||||
}
|
||||
run(&mut s, "component.activate", json!({"component":0}));
|
||||
let doc = s.doc.clone();
|
||||
let result = export(&mut s, camera(StandardView::Top), "dashed");
|
||||
assert_eq!(result["stats"]["bodies"], 3);
|
||||
assert_eq!(result["stats"]["shared_meshes"], 1);
|
||||
assert_eq!(result["stats"]["worker_limit"], meshes::WORKERS);
|
||||
assert!(result["hidden"].as_u64().unwrap() > 0);
|
||||
let lines = solidcraft_io::read_dxf(result["dxf"].as_str().unwrap()).unwrap();
|
||||
let mut centers = std::collections::BTreeSet::new();
|
||||
for line in lines {
|
||||
if let solidcraft_io::Geom2::Line(a, b) = line {
|
||||
// Each translated copy has a visible top perimeter, including the offscreen one.
|
||||
if (a.y - b.y).abs() > 5.9 {
|
||||
centers.insert(((a.x + 20.) / 15.).floor() as i64);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(centers.len() >= 3, "{centers:?}");
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc));
|
||||
}
|
||||
@@ -31,7 +31,7 @@ use serde_json::Value;
|
||||
use solidcraft_doc::{Document, Model, ModelState};
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
pub use cmd::{CommandInfo, CommandSpec, auto_operation, command_specs, extrude_reach, find_command};
|
||||
pub use cmd::{CommandInfo, CommandSpec, auto_operation, command_specs, find_command};
|
||||
pub use solidcraft_doc as doc;
|
||||
pub use solidcraft_doc::Visibility;
|
||||
pub use solidcraft_geom as geom;
|
||||
@@ -156,16 +156,6 @@ pub struct Snapshot {
|
||||
pub pending_moves: std::collections::BTreeMap<u64, solidcraft_doc::Mat>,
|
||||
}
|
||||
|
||||
/// A copy of a session that evaluates commands ahead of it ([`Session::ahead`]).
|
||||
pub struct Ahead(Session);
|
||||
|
||||
impl Ahead {
|
||||
/// Run `commands` (their results stay in the shared evaluation cache).
|
||||
pub fn evaluate(self, commands: &[(String, Value)]) -> Result<()> {
|
||||
self.0.preview_in_place(commands).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
/// What some commands would make, evaluated on a scratch copy of a session
|
||||
/// ([`Session::preview`]). The session itself is not changed.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -239,9 +229,6 @@ pub struct Session {
|
||||
pub section: Option<(Vec3, Vec3)>,
|
||||
/// Surface analysis shading the model (zebra, draft, curvature map).
|
||||
pub analysis: Option<SurfaceAnalysis>,
|
||||
/// 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<ContinuitySeam>,
|
||||
/// What is hidden or shown in the view (`browser.visibility`): saved with the design, not an
|
||||
/// undo step. A design brings its saved visibility when it opens (`Session::new`).
|
||||
pub visibility: Visibility,
|
||||
@@ -304,16 +291,6 @@ pub enum SurfaceAnalysis {
|
||||
Access { dir: Vec3 },
|
||||
}
|
||||
|
||||
/// One seam measured by `inspect.continuity`, where the viewport shades it: the stations it was
|
||||
/// sampled at, in world coordinates, and how it reads. View state only: the design is untouched.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct ContinuitySeam {
|
||||
/// Sample points along the seam, in world coordinates.
|
||||
pub points: Vec<Vec3>,
|
||||
/// The seam's worst verdict along its length.
|
||||
pub verdict: kernel::SeamVerdict,
|
||||
}
|
||||
|
||||
impl SurfaceAnalysis {
|
||||
/// How a picture shades the faces for this analysis.
|
||||
pub fn mode(self) -> render::AnalysisMode {
|
||||
@@ -369,7 +346,6 @@ impl Session {
|
||||
sketch_clipboard: None,
|
||||
section: None,
|
||||
analysis: None,
|
||||
continuity: Vec::new(),
|
||||
checkpoints: Vec::new(),
|
||||
next_checkpoint: 1,
|
||||
saved_visibility: visibility.clone(),
|
||||
@@ -837,7 +813,6 @@ impl Session {
|
||||
sketch_clipboard: self.sketch_clipboard.clone(),
|
||||
section: None,
|
||||
analysis: None,
|
||||
continuity: Vec::new(),
|
||||
checkpoints: Vec::new(),
|
||||
next_checkpoint: 1,
|
||||
visibility: self.visibility.clone(),
|
||||
@@ -912,17 +887,6 @@ impl Session {
|
||||
self.scratch().preview_in_place(commands).map(|(after, replies)| Preview { before: visible(self), after: visible(&after), replies })
|
||||
}
|
||||
|
||||
/// Run `commands` on a [`Session::scratch`] copy that keeps the undo and redo stacks: what
|
||||
/// they evaluate lands in the evaluation cache the copy shares with this session, so running
|
||||
/// them here afterwards finds it there. For a front end that computes a command which may
|
||||
/// take a while (undo, the history marker moved) off its window thread first.
|
||||
pub fn ahead(&self) -> Ahead {
|
||||
let mut copy = self.scratch();
|
||||
copy.undo.clone_from(&self.undo);
|
||||
copy.redo.clone_from(&self.redo);
|
||||
Ahead(copy)
|
||||
}
|
||||
|
||||
fn preview_in_place(mut self, commands: &[(String, Value)]) -> Result<(Self, Vec<Value>)> {
|
||||
if commands.is_empty() {
|
||||
return Err(EngineError::Other("nothing to preview".into()));
|
||||
|
||||
@@ -512,30 +512,6 @@ fn revolve_and_primitives() {
|
||||
assert!(rel(m["total"]["volume_mm3"].as_f64().unwrap(), PI * 125.0 * 5.0 / 2.0) < 5e-4);
|
||||
}
|
||||
|
||||
/// #726: a revolve swept each profile edge into two or three patches and left the planar ones
|
||||
/// apart, so a pick on such a face took part of it, and a sketch or an extrude there was refused
|
||||
/// ("the selected planar face no longer exists") until a later feature merged them.
|
||||
#[test]
|
||||
fn revolved_planar_faces_come_out_whole() {
|
||||
for angle in [360, 240] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XZ"}));
|
||||
run(&mut s, "sketch.line", json!({"points": [[8, 0], [30, 0], [30, -6], [18, -6], [18, -22], [8, -22]], "closed": true}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.revolve", json!({"axis": "Z", "angle": angle}));
|
||||
// Picks at 170°, in the last patch, which 240° covers whichever way it turns.
|
||||
let at = |r: f64, z: f64| json!([r * 170f64.to_radians().cos(), r * 170f64.to_radians().sin(), z]);
|
||||
// The flange's top annulus (z = 6, r 18…30), well inside it.
|
||||
let sk = run(&mut s, "sketch.create", json!({"plane": {"face": at(24.0, 6.0)}}));
|
||||
assert_eq!(sk["attachment"], "exact_face", "{angle}°: {sk}");
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
// The bottom annulus (z = 0, r 8…30).
|
||||
let v = volume(&mut s);
|
||||
run(&mut s, "solid.extrude", json!({"face": at(20.0, 0.0), "distance": 2, "operation": "join"}));
|
||||
assert!(volume(&mut s) > v + 1.0, "{angle}°: the extrude added nothing");
|
||||
}
|
||||
}
|
||||
|
||||
/// A spherical shell (a half ring between two arcs, both radial lines on the axis) revolved on a
|
||||
/// sketch plane that does not pass through the origin: the body is the shell, as it is on XY.
|
||||
/// Before, built in place, it measured a third too large (truck tessellates the degenerate faces
|
||||
@@ -1220,99 +1196,6 @@ fn extrude_auto_operation() {
|
||||
assert!(rel(volume(&mut s), 40.0 * 30.0 * 15.0 - 100.0 * 8.0) < 1e-6);
|
||||
}
|
||||
|
||||
/// #1666: a loft between two 18-point polylines has twisted (bilinear) side faces. Each was
|
||||
/// meshed as two flat triangles, which cross the surface; the mesh volume was 16 800.6 mm³
|
||||
/// against the B-rep's 17 884. Divided to the chord tolerance, the mesh matches the B-rep.
|
||||
#[test]
|
||||
fn twisted_ruled_faces_are_meshed_to_the_chord_tolerance() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Bottom"}));
|
||||
run(
|
||||
&mut s,
|
||||
"sketch.line",
|
||||
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24.76384,3],[-16.0568,14.97217],[-8,4.90117],[0,14.90117],[8,4.90117],[16.0568,14.97217],[24.76384,3],[26,3],[26,0],[23.23616,0],[15.9432,10.02783],[8,0.09883],[0,10.09883],[-8,0.09883],[-15.9432,10.02783],[-23.23616,0],[-26,0]]}),
|
||||
);
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 90.5, "name": "Top"}));
|
||||
run(
|
||||
&mut s,
|
||||
"sketch.line",
|
||||
json!({"closed": true, "infer": false, "connect": false, "points": [[-26,3],[-24,3],[-16,3],[-8,3],[0,3],[8,3],[16,3],[24,3],[26,3],[26,0],[24,0],[16,0],[8,0],[0,0],[-8,0],[-16,0],[-24,0],[-26,0]]}),
|
||||
);
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.loft", json!({"sections": [{"sketch": "Bottom"}, {"sketch": "Top"}], "operation": "new"}));
|
||||
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 volume: f64 = mesh
|
||||
.triangles
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let p = |i: u32| mesh.positions[i as usize];
|
||||
p(t[0]).dot(p(t[1]).cross(p(t[2]))) / 6.0
|
||||
})
|
||||
.sum();
|
||||
assert!(mesh.triangles.len() > 72, "the twisted faces are divided: {} triangles", mesh.triangles.len());
|
||||
assert!(rel(volume.abs(), exact) < 2e-3, "mesh {volume} against B-rep {exact}");
|
||||
}
|
||||
|
||||
/// #1633: to an object, the extrude goes to it on whichever side it is, whatever its
|
||||
/// `direction`: through the body to its far face is a Cut, out to something above is a Join.
|
||||
#[test]
|
||||
fn extrude_auto_operation_follows_the_to_object() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20}));
|
||||
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5, "corner": [0, 0, 50], "body_name": "Above"}));
|
||||
for direction in ["positive", "negative"] {
|
||||
// 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}");
|
||||
// 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}");
|
||||
}
|
||||
// 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));
|
||||
}
|
||||
|
||||
/// #1678: a hole's `position` takes length expressions, keeps them and follows the parameters: a
|
||||
/// hole on a plate's middle line stays there when the plate gets wider. A position of plain
|
||||
/// numbers is stored as before, with no `at`.
|
||||
#[test]
|
||||
fn a_hole_position_of_expressions_follows_the_parameters() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "parameters.add", json!({"name": "width", "expression": "30 mm"}));
|
||||
run(&mut s, "parameters.add", json!({"name": "t", "expression": "4 mm"}));
|
||||
run(&mut s, "solid.box", json!({"length": 100, "width": "width", "height": "t", "body_name": "Plate"}));
|
||||
run(&mut s, "solid.hole", json!({"position": ["40", "width/2", "t"], "clearance": "M5", "name": "Middle"}));
|
||||
run(&mut s, "solid.hole", json!({"position": [80, 10, 4], "clearance": "M5", "name": "Fixed"}));
|
||||
let centre_y = |s: &Session| {
|
||||
let st = s.model.state();
|
||||
solidcraft_kernel::measure(&st.body("Plate").unwrap().body).unwrap().centroid.y
|
||||
};
|
||||
let hole = |s: &Session, name: &str| -> Value {
|
||||
let saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
|
||||
saved["features"].as_array().and_then(|f| f.iter().find(|f| f["name"] == name)).cloned().unwrap()
|
||||
};
|
||||
assert_eq!(hole(&s, "Middle")["at"], json!([40.0, "width/2", "t"]), "the expressions are kept");
|
||||
assert!(hole(&s, "Fixed").get("at").is_none(), "plain numbers are stored as before");
|
||||
// The fixed hole sits off the middle line, so it alone moves the centre; widen the plate.
|
||||
let before = centre_y(&s);
|
||||
run(&mut s, "parameters.change", json!({"name": "width", "expression": "40 mm"}));
|
||||
let after = centre_y(&s);
|
||||
// The middle hole is at y = 20 now (the plate's middle); the fixed one stays at y = 10. With
|
||||
// the middle hole left at y = 15 the centre would sit lower still.
|
||||
let plate = 100.0 * 40.0 * 4.0;
|
||||
let hole_v = std::f64::consts::PI * (5.5f64 / 2.0).powi(2) * 4.0;
|
||||
let want = (plate * 20.0 - hole_v * 20.0 - hole_v * 10.0) / (plate - 2.0 * hole_v);
|
||||
assert!((after - want).abs() < 1e-3, "centre y {after}, want {want} (was {before})");
|
||||
// A bad expression is refused.
|
||||
assert!(s.execute("solid.hole", &json!({"position": ["40", "nope/2", "t"], "diameter": 3})).is_err());
|
||||
}
|
||||
|
||||
/// Additive extrusions default to joining even when only a profile side touches material.
|
||||
#[test]
|
||||
fn auto_extrude_joins_side_contact_elbow_and_keeps_new_body_explicit() {
|
||||
|
||||
@@ -22,18 +22,6 @@ fn volume(s: &mut Session, b: &str) -> f64 {
|
||||
|
||||
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)];
|
||||
|
||||
#[test]
|
||||
fn non_finite_thread_designations_are_refused_without_changing_the_design() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.cylinder", json!({"radius":4,"height":10}));
|
||||
let saved = s.doc.to_json();
|
||||
for designation in ["Minfx1", "M8xinf", "MNaNx1", "M8xNaN", "M1e999x1"] {
|
||||
let result = s.execute("solid.thread", &json!({"face":[4,0,2],"designation":designation}));
|
||||
assert!(result.is_err(), "{designation}: {result:?}");
|
||||
assert_eq!(s.doc.to_json(), saved);
|
||||
}
|
||||
}
|
||||
|
||||
/// ∫ 2π r · width(r) dr over [a, b]: the volume one turn of the groove takes out (a screw
|
||||
/// motion of a section in an axial plane sweeps 2π∫r dA per turn).
|
||||
fn per_turn(a: f64, b: f64, width: impl Fn(f64) -> f64) -> f64 {
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
//! Mesh export regressions: a closed body exports as a closed mesh.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_engine::Session;
|
||||
use solidcraft_io::{Format, export, read_3mf, read_stl};
|
||||
|
||||
fn run(s: &mut Session, script: Value) {
|
||||
for c in script.as_array().into_iter().flatten() {
|
||||
let (id, p) = (c["command"].as_str().unwrap_or_default(), &c["params"]);
|
||||
if let Err(e) = s.execute(id, p) {
|
||||
panic!("{id} {p}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edges (by vertex index) that are not used by exactly two triangles.
|
||||
fn open_edges(triangles: &[[u32; 3]]) -> Vec<((u32, u32), u32)> {
|
||||
let mut uses: HashMap<(u32, u32), u32> = HashMap::new();
|
||||
for t in triangles {
|
||||
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
*uses.entry((a.min(b), a.max(b))).or_default() += 1;
|
||||
}
|
||||
}
|
||||
uses.into_iter().filter(|(_, n)| *n != 2).collect()
|
||||
}
|
||||
|
||||
/// A bowl section (lines and arcs) revolved about Z, its rim cut by a large cylinder across it.
|
||||
/// The edge where the cylinder meets the inner cone is an intersection curve; one of its samples
|
||||
/// lay a few ten-thousandths of a millimetre off both surfaces, each face put the point on its
|
||||
/// own surface, and the exported mesh had a crack there (four edges used once).
|
||||
#[test]
|
||||
fn a_rim_cut_by_a_cylinder_exports_closed() {
|
||||
let mut s = Session::default();
|
||||
run(
|
||||
&mut s,
|
||||
json!([
|
||||
{"command": "sketch.create", "params": {"plane": "XZ", "name": "Section"}},
|
||||
{"command": "sketch.line", "params": {"points": [[0, 0], [48.8, 0], [50.0240096077, -1.2]]}},
|
||||
{"command": "sketch.arc.three_point", "params": {"start": [50.0240096077, -1.2], "end": [58.7867965644, -21.2132034356], "through": [52.5188160894, -12.0326443841]}},
|
||||
{"command": "sketch.line", "params": {"points": [[58.7867965644, -21.2132034356], [85.5735931288, -48], [82.1794805791, -48], [57.0897402896, -22.9102597104]]}},
|
||||
{"command": "sketch.arc.three_point", "params": {"start": [57.0897402896, -22.9102597104], "end": [48.3846976331, -7.0875], "through": [51.6125175266, -15.6176451113]}},
|
||||
{"command": "sketch.arc.three_point", "params": {"start": [48.3846976331, -7.0875], "end": [42.5300120096, -2.4], "through": [46.2800120096, -3.7162515012]}},
|
||||
{"command": "sketch.line", "params": {"points": [[42.5300120096, -2.4], [0, -2.4], [0, 0]]}},
|
||||
{"command": "sketch.finish", "params": {}},
|
||||
{"command": "solid.revolve", "params": {"sketch": "Section", "axis": "Z"}},
|
||||
{"command": "sketch.create", "params": {"plane": "YZ", "name": "RimCutter"}},
|
||||
{"command": "sketch.arc.three_point", "params": {"start": [-100, 11.6204810674], "end": [100, 46.4045454912], "through": [-52, 8]}},
|
||||
{"command": "sketch.line", "params": {"points": [[100, 46.4045454912], [100, 70], [-100, 70], [-100, 11.6204810674]]}},
|
||||
{"command": "sketch.finish", "params": {}},
|
||||
{"command": "solid.extrude", "params": {"sketch": "RimCutter", "distance": 200, "direction": "symmetric", "operation": "cut"}}
|
||||
]),
|
||||
);
|
||||
let st = s.model.state();
|
||||
assert_eq!(st.bodies.len(), 1);
|
||||
|
||||
let (objects, _) = read_3mf(&export(&st, &[], Format::ThreeMf, "cove").unwrap()).unwrap();
|
||||
assert_eq!(objects.len(), 1);
|
||||
let open = open_edges(&objects[0].triangles);
|
||||
assert!(open.is_empty(), "3MF: {} edges not used twice, e.g. {:?}", open.len(), open.first());
|
||||
|
||||
// STL has no indices: vertices are the same where their coordinates are.
|
||||
let mut index: HashMap<[u32; 3], u32> = HashMap::new();
|
||||
let triangles: Vec<[u32; 3]> = read_stl(&export(&st, &[], Format::StlBinary, "cove").unwrap())
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|t| {
|
||||
t.map(|p| {
|
||||
let n = index.len() as u32;
|
||||
*index.entry(p.map(f32::to_bits)).or_insert(n)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let open = open_edges(&triangles);
|
||||
assert!(open.is_empty(), "STL: {} edges not used twice, e.g. {:?}", open.len(), open.first());
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
//! Blend curves: one Bézier that joins two curves with a requested continuity order, by Hermite
|
||||
//! 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};
|
||||
|
||||
/// 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
|
||||
/// on [0, 1]. The derivative vectors are the reference curves' at the joints, measured in their
|
||||
/// own parameters and oriented the way the blend runs through the joint, so the blend agrees with
|
||||
/// each reference through its k-th derivative (G1, G2, G3, G4 for k = 1…4).
|
||||
///
|
||||
/// The two ends fix exactly half of the controls each: a Bézier's j-th forward difference is
|
||||
/// `P⁽ʲ⁾(0)·(n − j)!/n!`, so the first `k + 1` controls follow from the start data and the last
|
||||
/// `k + 1` from the end data, which meet exactly at the middle control. `None` when the ends
|
||||
/// disagree on the order, the order is above [`MAX_DERIVATIVE_ORDER`], or a value is not finite.
|
||||
pub fn hermite_bezier(p0: Vec2, p1: Vec2, d0: &[Vec2], d1: &[Vec2]) -> Option<Vec<Vec2>> {
|
||||
let k = d0.len();
|
||||
if k != d1.len() || k > MAX_DERIVATIVE_ORDER || !p0.is_finite() || !p1.is_finite() || d0.iter().chain(d1).any(|d| !d.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let n = 2 * k + 1;
|
||||
let mut c = vec![Vec2::ZERO; n + 1];
|
||||
c[0] = p0;
|
||||
for j in 1..=k {
|
||||
// `Δʲp₀ = P⁽ʲ⁾(0)·(n − j)!/n!`, and solving it for `pⱼ` puts `(−1)^(j − i + 1)` on every
|
||||
// control already known.
|
||||
let scale = 1.0 / (0..j).fold(1.0, |acc, i| acc * (n - i) as f64);
|
||||
let mut value = d0[j - 1] * scale;
|
||||
for (i, p) in c.iter().take(j).enumerate() {
|
||||
value += *p * (odd_sign(j - i) * binom(j, i));
|
||||
}
|
||||
c[j] = value;
|
||||
}
|
||||
c[n] = p1;
|
||||
for j in 1..=k {
|
||||
// The same at the far end, reading the controls backwards: `Σᵢ(−1)ⁱ·C(j,i)·pₙ₋ᵢ` is
|
||||
// `P⁽ʲ⁾(1)·(n − j)!/n!`, and solving that for `pₙ₋ⱼ` puts `(−1)^(j + i + 1)` on every control
|
||||
// already known.
|
||||
let scale = 1.0 / (0..j).fold(1.0, |acc, i| acc * (n - i) as f64);
|
||||
let mut value = d1[j - 1] * (scale * odd_sign(j + 1));
|
||||
for (i, p) in c[n - j + 1..].iter().rev().enumerate() {
|
||||
value += *p * (odd_sign(j + i) * binom(j, i));
|
||||
}
|
||||
c[n - j] = value;
|
||||
}
|
||||
c.iter().all(|p| p.is_finite()).then_some(c)
|
||||
}
|
||||
|
||||
/// `(−1)^(m + 1)`: the sign an m-th difference expansion carries in a Bézier's endpoint identity.
|
||||
fn odd_sign(m: usize) -> f64 {
|
||||
if m % 2 == 1 { 1.0 } else { -1.0 }
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
//! A bounding volume hierarchy over boxes: the nearest hit along a ray, or every item whose box
|
||||
//! passes a test, without looking at each item. Built once (median split on the widest axis of
|
||||
//! 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};
|
||||
|
||||
/// Most items in a leaf.
|
||||
const LEAF: usize = 4;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Node {
|
||||
bounds: Aabb3,
|
||||
/// A leaf: the first of its `count` items in [`Bvh::order`]. Otherwise its children are
|
||||
/// `first` and `first + 1`.
|
||||
first: u32,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// A hierarchy over boxes; items are the boxes' indices.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Bvh {
|
||||
nodes: Vec<Node>,
|
||||
order: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Bvh {
|
||||
/// The hierarchy over `boxes` (empty boxes are left out).
|
||||
pub fn new(boxes: &[Aabb3]) -> Bvh {
|
||||
let mut order: Vec<u32> =
|
||||
(0..boxes.len().min(u32::MAX as usize)).filter(|&i| boxes.get(i).is_some_and(|b| !b.is_empty() && finite(b))).map(|i| i as u32).collect();
|
||||
if order.is_empty() {
|
||||
return Bvh::default();
|
||||
}
|
||||
let item = |i: u32| boxes.get(i as usize).copied().unwrap_or(Aabb3::EMPTY);
|
||||
let centre = |i: u32| item(i).center();
|
||||
let mut nodes = vec![Node { bounds: Aabb3::EMPTY, first: 0, count: 0 }];
|
||||
// (node, start, end) in `order` still to be filled in.
|
||||
let mut todo = vec![(0usize, 0usize, order.len())];
|
||||
while let Some((n, start, end)) = todo.pop() {
|
||||
let Some(span) = order.get_mut(start..end) else { continue };
|
||||
let mut bounds = Aabb3::EMPTY;
|
||||
let mut centres = Aabb3::EMPTY;
|
||||
for &i in span.iter() {
|
||||
bounds = bounds.union(&item(i));
|
||||
centres.add(centre(i));
|
||||
}
|
||||
let size = centres.size();
|
||||
let axis = if size.x >= size.y && size.x >= size.z {
|
||||
0
|
||||
} else if size.y >= size.z {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let extent = [size.x, size.y, size.z][axis];
|
||||
if span.len() <= LEAF || !(extent > 0.0) {
|
||||
if let Some(node) = nodes.get_mut(n) {
|
||||
*node = Node { bounds, first: start as u32, count: span.len() as u32 };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let key = |i: &u32| {
|
||||
let c = centre(*i);
|
||||
[c.x, c.y, c.z][axis]
|
||||
};
|
||||
let mid = span.len() / 2;
|
||||
span.select_nth_unstable_by(mid, |a, b| key(a).total_cmp(&key(b)));
|
||||
let left = nodes.len();
|
||||
nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 });
|
||||
nodes.push(Node { bounds: Aabb3::EMPTY, first: 0, count: 0 });
|
||||
if let Some(node) = nodes.get_mut(n) {
|
||||
*node = Node { bounds, first: left as u32, count: 0 };
|
||||
}
|
||||
todo.push((left, start, start + mid));
|
||||
todo.push((left + 1, start + mid, end));
|
||||
}
|
||||
Bvh { nodes, order }
|
||||
}
|
||||
|
||||
/// The box around everything (empty for no items).
|
||||
pub fn bounds(&self) -> Aabb3 {
|
||||
self.nodes.first().map_or(Aabb3::EMPTY, |n| n.bounds)
|
||||
}
|
||||
|
||||
/// Calls `item` with every item in a leaf whose box, and every box above it, `enter` accepts.
|
||||
pub fn visit(&self, mut enter: impl FnMut(&Aabb3) -> bool, mut item: impl FnMut(u32)) {
|
||||
let mut stack = vec![0usize];
|
||||
while let Some(n) = stack.pop() {
|
||||
let Some(node) = self.nodes.get(n) else { continue };
|
||||
if !enter(&node.bounds) {
|
||||
continue;
|
||||
}
|
||||
if node.count > 0 {
|
||||
let (a, b) = (node.first as usize, node.first as usize + node.count as usize);
|
||||
for &i in self.order.get(a..b).unwrap_or(&[]) {
|
||||
item(i);
|
||||
}
|
||||
} else {
|
||||
stack.push(node.first as usize + 1);
|
||||
stack.push(node.first as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest item along the ray from `o` along `d`: `hit` gives an item's distance along
|
||||
/// `d` (`None`: missed). Equal distances go to the lowest item, as a scan in item order
|
||||
/// keeping strictly nearer hits would answer. Boxes are entered nearest first, and one that
|
||||
/// starts past the best hit so far is skipped.
|
||||
pub fn nearest(&self, o: Vec3, d: Vec3, mut hit: impl FnMut(u32) -> Option<f64>) -> Option<(f64, u32)> {
|
||||
if ![o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z);
|
||||
let mut best: Option<(f64, u32)> = None;
|
||||
let root = self.nodes.first().and_then(|n| ray_box(o, d, inv, &n.bounds, 0.0))?;
|
||||
let mut stack = vec![(0usize, root)];
|
||||
while let Some((n, t0)) = stack.pop() {
|
||||
if best.is_some_and(|(bt, _)| t0 > bt) {
|
||||
continue;
|
||||
}
|
||||
let Some(node) = self.nodes.get(n) else { continue };
|
||||
if node.count > 0 {
|
||||
let (a, b) = (node.first as usize, node.first as usize + node.count as usize);
|
||||
for &i in self.order.get(a..b).unwrap_or(&[]) {
|
||||
if let Some(t) = hit(i)
|
||||
&& best.is_none_or(|(bt, bi)| t < bt || (t == bt && i < bi))
|
||||
{
|
||||
best = Some((t, i));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (l, r) = (node.first as usize, node.first as usize + 1);
|
||||
let tl = self.nodes.get(l).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0));
|
||||
let tr = self.nodes.get(r).and_then(|c| ray_box(o, d, inv, &c.bounds, 0.0));
|
||||
// The nearer child is popped first.
|
||||
match (tl, tr) {
|
||||
(Some(a), Some(b)) if a <= b => stack.extend([(r, b), (l, a)]),
|
||||
(Some(a), Some(b)) => stack.extend([(l, a), (r, b)]),
|
||||
(Some(a), None) => stack.push((l, a)),
|
||||
(None, Some(b)) => stack.push((r, b)),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
fn finite(b: &Aabb3) -> bool {
|
||||
[b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().all(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Where the ray from `o` along `d` (`inv` = 1 / `d` per axis) enters box `b` grown by `pad`,
|
||||
/// from 0 on; `None` when it misses or the box lies behind.
|
||||
fn ray_box(o: Vec3, d: Vec3, inv: Vec3, b: &Aabb3, pad: f64) -> Option<f64> {
|
||||
let (mut t0, mut t1) = (0.0f64, f64::INFINITY);
|
||||
for (o, d, inv, lo, hi) in [(o.x, d.x, inv.x, b.min.x, b.max.x), (o.y, d.y, inv.y, b.min.y, b.max.y), (o.z, d.z, inv.z, b.min.z, b.max.z)] {
|
||||
let (lo, hi) = (lo - pad, hi + pad);
|
||||
if d == 0.0 || !inv.is_finite() {
|
||||
if o < lo || o > hi {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (a, b) = ((lo - o) * inv, (hi - o) * inv);
|
||||
let (a, b) = if a <= b { (a, b) } else { (b, a) };
|
||||
t0 = t0.max(a);
|
||||
t1 = t1.min(b);
|
||||
if t0 > t1 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(t0 <= t1).then_some(t0)
|
||||
}
|
||||
|
||||
/// The farthest any corner of `b` lies along `d` from `o` (0 when the box is behind).
|
||||
fn farthest_along(o: Vec3, d: Vec3, b: &Aabb3) -> f64 {
|
||||
let along = |lo: f64, hi: f64, o: f64, d: f64| if d >= 0.0 { (hi - o) * d } else { (lo - o) * d };
|
||||
(along(b.min.x, b.max.x, o.x, d.x) + along(b.min.y, b.max.y, o.y, d.y) + along(b.min.z, b.max.z, o.z, d.z)).max(0.0)
|
||||
}
|
||||
|
||||
/// A mesh's triangles and edge segments in hierarchies, for picking: the nearest triangle along
|
||||
/// a ray, and the edge segments near one. Built from one mesh and answers only for it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct MeshIndex {
|
||||
triangles: Bvh,
|
||||
triangle_count: usize,
|
||||
segments: Bvh,
|
||||
/// Per segment item: its edge, and its first point in that edge's polyline.
|
||||
segment_of: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl MeshIndex {
|
||||
/// The index of `mesh`.
|
||||
pub fn new(mesh: &Mesh) -> MeshIndex {
|
||||
let pad = |mut b: Aabb3| {
|
||||
// Flat boxes (a triangle square to an axis) are grown a little, so a ray through
|
||||
// them is never lost to rounding in the box test.
|
||||
let scale = [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z].iter().fold(1.0f64, |m, v| m.max(v.abs()));
|
||||
let e = scale * 1e-9;
|
||||
b.min -= Vec3::new(e, e, e);
|
||||
b.max += Vec3::new(e, e, e);
|
||||
b
|
||||
};
|
||||
let boxes: Vec<Aabb3> = mesh
|
||||
.triangles
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let mut b = Aabb3::EMPTY;
|
||||
for p in mesh.tri(t).into_iter().flatten() {
|
||||
b.add(p);
|
||||
}
|
||||
if b.is_empty() { b } else { pad(b) }
|
||||
})
|
||||
.collect();
|
||||
let mut segment_of = Vec::new();
|
||||
let mut seg_boxes = Vec::new();
|
||||
for (ei, e) in mesh.edges.iter().enumerate() {
|
||||
// A one-point edge still has its vertex: it stands as a segment from it to itself.
|
||||
let n = if e.len() == 1 { 1 } else { e.len().saturating_sub(1) };
|
||||
for si in 0..n {
|
||||
let (Some(a), Some(b)) = (e.get(si), e.get(si + 1).or(e.get(si))) else { continue };
|
||||
let mut bx = Aabb3::EMPTY;
|
||||
bx.add(*a);
|
||||
bx.add(*b);
|
||||
seg_boxes.push(pad(bx));
|
||||
segment_of.push((ei as u32, si as u32));
|
||||
}
|
||||
}
|
||||
MeshIndex { triangles: Bvh::new(&boxes), triangle_count: mesh.triangles.len(), segments: Bvh::new(&seg_boxes), segment_of }
|
||||
}
|
||||
|
||||
/// [`Mesh::raycast`] through the index: the same answer, including which triangle wins a tie.
|
||||
/// For a mesh other than the one indexed, the plain scan answers.
|
||||
pub fn raycast(&self, mesh: &Mesh, o: Vec3, dir: Vec3) -> Option<(f64, usize)> {
|
||||
if mesh.triangles.len() != self.triangle_count {
|
||||
return mesh.raycast(o, dir);
|
||||
}
|
||||
let frame = crate::mesh::RayFrame::new(o, dir)?;
|
||||
self.triangles
|
||||
.nearest(o, dir, |i| mesh.triangles.get(i as usize).and_then(|t| mesh.tri(t)).and_then(|p| frame.hit(p)))
|
||||
.map(|(t, i)| (t, i as usize))
|
||||
}
|
||||
|
||||
/// Calls `f(edge, first point)` for every edge segment that may come within `a + b·t` of the
|
||||
/// ray from `o` along unit `d`, `t` being the distance along it (each at most once). A
|
||||
/// constant `a` suits an orthographic view; a perspective view widens with `b`.
|
||||
pub fn segments_near(&self, o: Vec3, d: Vec3, a: f64, b: f64, mut f: impl FnMut(usize, usize)) {
|
||||
if ![a, b, o.x, o.y, o.z, d.x, d.y, d.z].iter().all(|v| v.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let inv = Vec3::new(1.0 / d.x, 1.0 / d.y, 1.0 / d.z);
|
||||
self.segments.visit(
|
||||
|bx| {
|
||||
let reach = a.max(0.0) + b.max(0.0) * farthest_along(o, d, bx);
|
||||
ray_box(o, d, inv, bx, reach).is_some()
|
||||
},
|
||||
|i| {
|
||||
if let Some((e, s)) = self.segment_of.get(i as usize) {
|
||||
f(*e as usize, *s as usize);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bvh_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,130 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
/// A small deterministic generator (the tests need no crate for randomness).
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> f64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(self.0 >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
fn range(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (hi - lo) * self.next()
|
||||
}
|
||||
fn vec(&mut self, r: f64) -> Vec3 {
|
||||
Vec3::new(self.range(-r, r), self.range(-r, r), self.range(-r, r))
|
||||
}
|
||||
}
|
||||
|
||||
/// A grid of `n` × `n` squares of two triangles on z = 0, and `extra` random triangles above.
|
||||
fn mesh(n: u32, extra: usize, rng: &mut Lcg) -> Mesh {
|
||||
let mut positions: Vec<Vec3> = (0..=n).flat_map(|j| (0..=n).map(move |i| Vec3::new(f64::from(i), f64::from(j), 0.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)]);
|
||||
}
|
||||
}
|
||||
for _ in 0..extra {
|
||||
let c = rng.vec(f64::from(n)) + Vec3::new(0.0, 0.0, f64::from(n));
|
||||
let k = positions.len() as u32;
|
||||
positions.extend([c + rng.vec(1.5), c + rng.vec(1.5), c + rng.vec(1.5)]);
|
||||
triangles.push([k, k + 1, k + 2]);
|
||||
}
|
||||
let edges =
|
||||
(0..n).map(|i| (0..=n).map(|j| Vec3::new(f64::from(i), f64::from(j), 0.0)).collect()).chain([vec![Vec3::new(0.5, 0.5, 2.0)]]).collect();
|
||||
Mesh { tri_face: vec![0; triangles.len()], positions, triangles, edges, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_raycast_answers_as_the_scan_does() {
|
||||
let mut rng = Lcg(7);
|
||||
let m = mesh(12, 400, &mut rng);
|
||||
let index = MeshIndex::new(&m);
|
||||
let mut hits = 0;
|
||||
for k in 0..4000 {
|
||||
// Every few rays go straight down through grid vertices and edges, where two or more
|
||||
// triangles tie.
|
||||
let (o, d) = if k % 4 == 0 {
|
||||
let p = Vec3::new(f64::from(k % 13), f64::from((k / 13) % 13) * 0.5, 50.0);
|
||||
(p, Vec3::new(0.0, 0.0, -1.0))
|
||||
} else {
|
||||
let o = rng.vec(40.0) + Vec3::new(6.0, 6.0, 0.0);
|
||||
let target = Vec3::new(rng.range(-1.0, 13.0), rng.range(-1.0, 13.0), rng.range(-2.0, 14.0));
|
||||
let Some(d) = (target - o).normalized() else { continue };
|
||||
(o, d)
|
||||
};
|
||||
let want = m.raycast(o, d);
|
||||
assert_eq!(index.raycast(&m, o, d), want, "ray {k} from {o:?} along {d:?}");
|
||||
hits += usize::from(want.is_some());
|
||||
}
|
||||
assert!(hits > 1000, "the rays should mostly hit ({hits})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_raycast_of_another_mesh_falls_back_to_the_scan() {
|
||||
let mut rng = Lcg(3);
|
||||
let (a, b) = (mesh(2, 0, &mut rng), mesh(5, 0, &mut rng));
|
||||
let index = MeshIndex::new(&a);
|
||||
let (o, d) = (Vec3::new(4.5, 4.2, 9.0), Vec3::new(0.0, 0.0, -1.0));
|
||||
assert!(b.raycast(o, d).is_some());
|
||||
assert_eq!(index.raycast(&b, o, d), b.raycast(o, d));
|
||||
}
|
||||
|
||||
/// Distance from point `p` to the ray from `o` along unit `d` (from its start on), and how far along.
|
||||
fn ray_point(o: Vec3, d: Vec3, p: Vec3) -> (f64, f64) {
|
||||
let t = (p - o).dot(d).max(0.0);
|
||||
((o + d * t).dist(p), t)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn segments_near_the_ray_are_all_reported() {
|
||||
let mut rng = Lcg(11);
|
||||
let m = mesh(16, 0, &mut rng);
|
||||
let index = MeshIndex::new(&m);
|
||||
for k in 0..500 {
|
||||
let o = rng.vec(30.0) + Vec3::new(8.0, 8.0, 30.0);
|
||||
let target = Vec3::new(rng.range(0.0, 16.0), rng.range(0.0, 16.0), 0.0);
|
||||
let Some(d) = (target - o).normalized() else { continue };
|
||||
let (a, b) = if k % 2 == 0 { (0.3, 0.0) } else { (0.0, 0.01) };
|
||||
let mut got = std::collections::HashSet::new();
|
||||
index.segments_near(o, d, a, b, |e, s| {
|
||||
assert!(got.insert((e, s)), "segment {e}/{s} reported twice");
|
||||
});
|
||||
for (ei, e) in m.edges.iter().enumerate() {
|
||||
for (si, w) in e.windows(2).enumerate() {
|
||||
// Sampled along the segment: any point within reach must have its segment reported.
|
||||
for f in 0..=8 {
|
||||
let p = w[0] + (w[1] - w[0]) * (f64::from(f) / 8.0);
|
||||
let (dist, t) = ray_point(o, d, p);
|
||||
if dist <= a + b * t {
|
||||
assert!(got.contains(&(ei, si)), "ray {k}: segment {ei}/{si} is within reach but was not reported");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The one-point edge stands as its own segment.
|
||||
let last = m.edges.len() - 1;
|
||||
let (dist, t) = ray_point(o, d, Vec3::new(0.5, 0.5, 2.0));
|
||||
if dist <= a + b * t {
|
||||
assert!(got.contains(&(last, 0)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_boxes_never_panic() {
|
||||
let nan = Vec3::new(f64::NAN, 0.0, 0.0);
|
||||
let boxes = [Aabb3::EMPTY, Aabb3 { min: nan, max: nan }, Aabb3 { min: Vec3::ZERO, max: Vec3::new(1.0, 1.0, 1.0) }];
|
||||
let bvh = Bvh::new(&boxes);
|
||||
assert_eq!(bvh.nearest(Vec3::new(0.5, 0.5, 5.0), Vec3::new(0.0, 0.0, -1.0), |i| Some(f64::from(i))), Some((2.0, 2)));
|
||||
assert_eq!(bvh.nearest(Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 0.0), |_| Some(1.0)), None);
|
||||
let empty = Bvh::new(&[]);
|
||||
assert!(empty.nearest(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), |_| Some(1.0)).is_none());
|
||||
empty.visit(|_| true, |_| panic!("an empty hierarchy has no items"));
|
||||
let m = Mesh { positions: vec![Vec3::ZERO], triangles: vec![[0, 5, 9]], ..Default::default() };
|
||||
assert!(MeshIndex::new(&m).raycast(&m, Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 0.0, -1.0)).is_none());
|
||||
MeshIndex::new(&m).segments_near(Vec3::ZERO, Vec3::new(0.0, 0.0, 1.0), f64::NAN, 0.0, |_, _| panic!("no segments"));
|
||||
}
|
||||
@@ -9,10 +9,8 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod arcfit;
|
||||
pub mod blend;
|
||||
pub mod brep;
|
||||
pub mod bspline;
|
||||
mod bvh;
|
||||
pub mod compare;
|
||||
pub mod env;
|
||||
pub mod fill;
|
||||
@@ -25,11 +23,9 @@ pub mod tspline;
|
||||
mod vec;
|
||||
|
||||
pub use arcfit::MAX_FIT_PIECES;
|
||||
pub use blend::hermite_bezier;
|
||||
pub use bvh::{Bvh, MeshIndex};
|
||||
pub use mesh::{Aabb3, BoxedTriangle, InsideIndex, MassProperties, Mesh, MeshMeasure, find_close_pair};
|
||||
pub use plane::Plane;
|
||||
pub use profile::{Loop2, MAX_BEZIER_CTRL, MAX_BEZIER_DEGREE, MAX_DERIVATIVE_ORDER, Region2, Seg2, bezier, regions_apart};
|
||||
pub use profile::{Loop2, MAX_BEZIER_DEGREE, Region2, Seg2, bezier, regions_apart};
|
||||
pub use vec::{Vec2, Vec3};
|
||||
|
||||
/// Geometric tolerance for coincidence tests (mm).
|
||||
|
||||
+33
-57
@@ -559,39 +559,13 @@ impl Mesh {
|
||||
/// two triangles that share an edge get exactly opposite values there. A ray through a
|
||||
/// shared edge or vertex hits at least one of them; it never slips between them.
|
||||
pub fn raycast(&self, o: Vec3, dir: Vec3) -> Option<(f64, usize)> {
|
||||
let frame = RayFrame::new(o, dir)?;
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (i, t) in self.triangles.iter().enumerate() {
|
||||
let Some(p) = self.tri(t) else { continue };
|
||||
if let Some(t) = frame.hit(p)
|
||||
&& best.is_none_or(|(bt, _)| t < bt)
|
||||
{
|
||||
best = Some((t, i));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
/// A ray in the frame of [`Mesh::raycast`]'s watertight test: its dominant axis becomes z; x and
|
||||
/// y follow it cyclically, swapped to keep the frame right-handed when the ray runs towards −z.
|
||||
pub(crate) struct RayFrame {
|
||||
o: Vec3,
|
||||
k: [usize; 3],
|
||||
s: [f64; 3],
|
||||
}
|
||||
|
||||
fn comp(v: Vec3, k: usize) -> f64 {
|
||||
match k {
|
||||
0 => v.x,
|
||||
1 => v.y,
|
||||
_ => v.z,
|
||||
}
|
||||
}
|
||||
|
||||
impl RayFrame {
|
||||
/// `None` for a direction that is zero or not finite.
|
||||
pub(crate) fn new(o: Vec3, dir: Vec3) -> Option<RayFrame> {
|
||||
let comp = |v: Vec3, k: usize| match k {
|
||||
0 => v.x,
|
||||
1 => v.y,
|
||||
_ => v.z,
|
||||
};
|
||||
// The ray's dominant axis becomes z; x and y follow it cyclically, swapped to keep
|
||||
// the frame right-handed when the ray runs towards −z.
|
||||
let a = [dir.x.abs(), dir.y.abs(), dir.z.abs()];
|
||||
let kz = if a[0] >= a[1] && a[0] >= a[2] {
|
||||
0
|
||||
@@ -608,31 +582,33 @@ impl RayFrame {
|
||||
if dz < 0.0 {
|
||||
std::mem::swap(&mut kx, &mut ky);
|
||||
}
|
||||
Some(RayFrame { o, k: [kx, ky, kz], s: [comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz] })
|
||||
}
|
||||
|
||||
/// A vertex in the ray's frame: (x, y) across the ray, z scaled along it.
|
||||
fn frame(&self, p: Vec3) -> (f64, f64, f64) {
|
||||
let q = p - self.o;
|
||||
let z = comp(q, self.k[2]);
|
||||
(comp(q, self.k[0]) - self.s[0] * z, comp(q, self.k[1]) - self.s[1] * z, self.s[2] * z)
|
||||
}
|
||||
|
||||
/// The distance along the ray to triangle `[pa, pb, pc]` (`None`: missed, or not in front).
|
||||
pub(crate) fn hit(&self, [pa, pb, pc]: [Vec3; 3]) -> Option<f64> {
|
||||
let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (self.frame(pa), self.frame(pb), self.frame(pc));
|
||||
let u = cx * by - cy * bx;
|
||||
let v = ax * cy - ay * cx;
|
||||
let w = bx * ay - by * ax;
|
||||
if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
|
||||
return None;
|
||||
let (sx, sy, sz) = (comp(dir, kx) / dz, comp(dir, ky) / dz, 1.0 / dz);
|
||||
// A vertex in the ray's frame: (x, y) across the ray, z scaled along it.
|
||||
let frame = |p: Vec3| {
|
||||
let q = p - o;
|
||||
let z = comp(q, kz);
|
||||
(comp(q, kx) - sx * z, comp(q, ky) - sy * z, sz * z)
|
||||
};
|
||||
let mut best: Option<(f64, usize)> = None;
|
||||
for (i, t) in self.triangles.iter().enumerate() {
|
||||
let Some([pa, pb, pc]) = self.tri(t) else { continue };
|
||||
let ((ax, ay, az), (bx, by, bz), (cx, cy, cz)) = (frame(pa), frame(pb), frame(pc));
|
||||
let u = cx * by - cy * bx;
|
||||
let v = ax * cy - ay * cx;
|
||||
let w = bx * ay - by * ax;
|
||||
if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let det = u + v + w;
|
||||
if det == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let t = (u * az + v * bz + w * cz) / det;
|
||||
if t.is_finite() && t > 1e-9 && best.is_none_or(|(bt, _)| t < bt) {
|
||||
best = Some((t, i));
|
||||
}
|
||||
}
|
||||
let det = u + v + w;
|
||||
if det == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let t = (u * az + v * bz + w * cz) / det;
|
||||
(t.is_finite() && t > 1e-9).then_some(t)
|
||||
best
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-131
@@ -38,35 +38,26 @@ pub enum Seg2 {
|
||||
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.
|
||||
/// Bézier of degree `n` (4…7) over `p[0..=n]` (the rest unused): pieces of higher-degree
|
||||
/// splines.
|
||||
Bezier {
|
||||
n: u8,
|
||||
p: [Vec2; MAX_BEZIER_CTRL],
|
||||
p: [Vec2; 8],
|
||||
},
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// Highest degree of [`Seg2::Bezier`].
|
||||
pub const MAX_BEZIER_DEGREE: usize = 7;
|
||||
|
||||
/// 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
|
||||
/// continuity order a blend curve can be built for (4 = G4).
|
||||
pub const MAX_DERIVATIVE_ORDER: usize = 4;
|
||||
|
||||
/// A Bézier segment over `pts` (2…[`MAX_BEZIER_CTRL`] points): a line, a cubic or a higher-degree
|
||||
/// piece. A quadratic becomes a conic of weight 1.
|
||||
/// A Bézier segment over `pts` (2…8 points): a line, a cubic or a higher-degree piece. A
|
||||
/// quadratic becomes a conic of weight 1.
|
||||
pub fn bezier(pts: &[Vec2]) -> Option<Seg2> {
|
||||
Some(match *pts {
|
||||
[a, b] => Seg2::Line { a, b },
|
||||
[a, apex, b] => Seg2::Conic { a, apex, b, w: 1.0 },
|
||||
[p0, p1, p2, p3] => Seg2::Cubic { p0, p1, p2, p3 },
|
||||
_ if (2..=MAX_BEZIER_CTRL).contains(&pts.len()) => {
|
||||
let mut p = [Vec2::ZERO; MAX_BEZIER_CTRL];
|
||||
_ if pts.len() <= MAX_BEZIER_DEGREE + 1 => {
|
||||
let mut p = [Vec2::ZERO; 8];
|
||||
for (d, s) in p.iter_mut().zip(pts) {
|
||||
*d = *s;
|
||||
}
|
||||
@@ -95,38 +86,6 @@ fn casteljau(c: &[Vec2], t: f64) -> (Vec2, Vec<Vec2>, Vec<Vec2>) {
|
||||
(left.last().copied().unwrap_or(Vec2::ZERO), left, right)
|
||||
}
|
||||
|
||||
/// Binomial coefficient `C(n, k)` for the small orders the derivative rules need (0 when
|
||||
/// `k > n`).
|
||||
pub(crate) fn binom(n: usize, k: usize) -> f64 {
|
||||
if k > n {
|
||||
return 0.0;
|
||||
}
|
||||
(0..k.min(n - k)).fold(1.0, |v, i| v * (n - i) as f64 / (i + 1) as f64)
|
||||
}
|
||||
|
||||
/// Derivatives 1…`order` of the Bézier over `c` (degree `c.len() - 1`) at `t`: the j-th forward
|
||||
/// difference of the control polygon, scaled by `n!/(n − j)!` and evaluated by de Casteljau.
|
||||
/// Exact in exact arithmetic, zero above the degree, `None` for non-finite input.
|
||||
fn bezier_derivatives(c: &[Vec2], t: f64, order: usize) -> Option<Vec<Vec2>> {
|
||||
if !t.is_finite() || c.is_empty() || c.iter().any(|p| !p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let n = c.len() - 1;
|
||||
let mut diffs = c.to_vec();
|
||||
let mut scale = 1.0;
|
||||
let mut out = Vec::with_capacity(order);
|
||||
for j in 1..=order {
|
||||
if diffs.len() < 2 {
|
||||
out.push(Vec2::ZERO);
|
||||
continue;
|
||||
}
|
||||
diffs = diffs.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
scale *= (n + 1 - j) as f64;
|
||||
out.push(casteljau(&diffs, t).0 * scale);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Gauss–Legendre nodes and weights on [0, 1] (5 points).
|
||||
const GL5: [(f64, f64); 5] = [
|
||||
(0.046_910_077_030_668, 0.118_463_442_528_095),
|
||||
@@ -137,7 +96,7 @@ const GL5: [(f64, f64); 5] = [
|
||||
];
|
||||
|
||||
impl Seg2 {
|
||||
fn bez(n: u8, p: &[Vec2; MAX_BEZIER_CTRL]) -> &[Vec2] {
|
||||
fn bez(n: u8, p: &[Vec2; 8]) -> &[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).
|
||||
@@ -162,86 +121,6 @@ impl Seg2 {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// 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<Vec<Vec2>> {
|
||||
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,
|
||||
|
||||
@@ -560,161 +560,3 @@ mod close_pairs {
|
||||
assert!(budget < 10_000_000, "work was counted");
|
||||
}
|
||||
}
|
||||
|
||||
mod blend {
|
||||
use super::*;
|
||||
|
||||
/// `j!` for the small orders the Hermite and quotient identities use.
|
||||
fn fact(j: usize) -> f64 {
|
||||
(1..=j).fold(1.0, |a, b| a * b as f64)
|
||||
}
|
||||
|
||||
/// The derivatives 1…`order` a Bézier's control polygon carries at its end `at_end`: the j-th
|
||||
/// difference of the controls, scaled by `n!/(n − j)!`. This is the textbook endpoint identity
|
||||
/// of a Bézier, written here independently of the library's.
|
||||
fn control_derivatives(ctrl: &[Vec2], at_end: bool, order: usize) -> Vec<Vec2> {
|
||||
let c: Vec<Vec2> = if at_end { ctrl.iter().rev().copied().collect() } else { ctrl.to_vec() };
|
||||
let n = c.len() - 1;
|
||||
let (mut diffs, mut scale) = (c, 1.0);
|
||||
let mut out = Vec::new();
|
||||
for j in 1..=order {
|
||||
diffs = diffs.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
scale *= (n + 1 - j) as f64;
|
||||
out.push(diffs.first().copied().unwrap_or_default() * scale);
|
||||
}
|
||||
// The reversed controls describe `P(1 − s)`, so reversing again to read the original
|
||||
// parameterisation negates the odd orders.
|
||||
if at_end {
|
||||
for (i, v) in out.iter_mut().enumerate() {
|
||||
if i % 2 == 0 {
|
||||
*v = -*v;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hermite_bezier_meets_the_derivative_data_at_both_ends() {
|
||||
let (p0, p1) = (Vec2::new(1.0, 2.0), Vec2::new(-3.0, 4.5));
|
||||
let d0 = [Vec2::new(2.0, 1.0), Vec2::new(-0.5, 3.0), Vec2::new(1.5, 1.0), Vec2::new(0.25, -2.0)];
|
||||
let d1 = [Vec2::new(-1.0, 0.5), Vec2::new(2.0, -1.5), Vec2::new(-0.75, 0.5), Vec2::new(3.0, 1.25)];
|
||||
for k in 0..=MAX_DERIVATIVE_ORDER {
|
||||
let cps = hermite_bezier(p0, p1, &d0[..k], &d1[..k]).unwrap();
|
||||
assert_eq!(cps.len(), 2 * k + 2, "degree 2k+1 has 2k+2 controls");
|
||||
assert_eq!(cps[0], p0);
|
||||
assert_eq!(*cps.last().unwrap(), p1);
|
||||
for (got, want) in control_derivatives(&cps, false, k).iter().zip(&d0[..k]) {
|
||||
assert!(got.dist(*want) < 1e-11, "k={k} at t=0: {got:?} vs {want:?}");
|
||||
}
|
||||
for (got, want) in control_derivatives(&cps, true, k).iter().zip(&d1[..k]) {
|
||||
assert!(got.dist(*want) < 1e-11, "k={k} at t=1: {got:?} vs {want:?}");
|
||||
}
|
||||
// The piece is exactly the single Bézier `bezier` hands back, and its ends are the two
|
||||
// joints.
|
||||
let seg = bezier(&cps).unwrap();
|
||||
assert!(seg.start().dist(p0) < 1e-12 && seg.end().dist(p1) < 1e-12);
|
||||
for (got, want) in seg.derivatives(0.0, k).unwrap().iter().zip(&d0[..k]) {
|
||||
assert!(got.dist(*want) < 1e-10, "k={k} at t=0: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hermite_bezier_refuses_hostile_data() {
|
||||
let (p0, p1) = (Vec2::ZERO, Vec2::X);
|
||||
let d = [Vec2::Y, Vec2::X];
|
||||
assert!(hermite_bezier(p0, p1, &d, &d).is_some());
|
||||
assert!(hermite_bezier(p0, p1, &d, &d[..1]).is_none(), "the ends must agree on the order");
|
||||
assert!(hermite_bezier(p0, p1, &[Vec2::ZERO; 5], &[Vec2::ZERO; 5]).is_none(), "order above G4");
|
||||
assert!(hermite_bezier(Vec2::new(f64::NAN, 0.0), p1, &[], &[]).is_none());
|
||||
assert!(hermite_bezier(p0, p1, &[Vec2::new(f64::INFINITY, 0.0)], &[Vec2::Y]).is_none());
|
||||
assert!(hermite_bezier(p0, p1, &[], &[Vec2::Y]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seg_derivatives_are_exact_for_lines_and_polynomial_pieces() {
|
||||
let line = Seg2::Line { a: Vec2::new(-1.0, 2.0), b: Vec2::new(3.0, 5.0) };
|
||||
let d = line.derivatives(0.0, MAX_DERIVATIVE_ORDER).unwrap();
|
||||
assert!(d[0].dist(Vec2::new(4.0, 3.0)) < 1e-12);
|
||||
assert_eq!(d[1].len() + d[2].len() + d[3].len(), 0.0, "a line has no curvature");
|
||||
let cubic = Seg2::Cubic { p0: Vec2::new(0.0, 0.0), p1: Vec2::new(3.0, 9.0), p2: Vec2::new(7.0, -4.0), p3: Vec2::new(11.0, 2.0) };
|
||||
let ctrl = [Vec2::new(0.0, 0.0), Vec2::new(3.0, 9.0), Vec2::new(7.0, -4.0), Vec2::new(11.0, 2.0)];
|
||||
for (t, at_end) in [(0.0, false), (1.0, true)] {
|
||||
for (got, want) in cubic.derivatives(t, MAX_DERIVATIVE_ORDER).unwrap().iter().zip(control_derivatives(&ctrl, at_end, 4)) {
|
||||
assert!(got.dist(want) < 1e-9, "t={t}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
for t in [0.0, 0.35, 1.0] {
|
||||
assert!(cubic.derivatives(t, 1).unwrap()[0].dist(cubic.derivative(t)) < 1e-9, "t={t}");
|
||||
}
|
||||
// A degree-9 piece (the G4 blend's own shape) at both ends.
|
||||
let pts: Vec<Vec2> = (0..10).map(|i| Vec2::new(i as f64 * 0.7, (i as f64 * 1.3).sin())).collect();
|
||||
let seg = bezier(&pts).unwrap();
|
||||
assert!(matches!(seg, Seg2::Bezier { n: 9, .. }));
|
||||
for (t, at_end) in [(0.0, false), (1.0, true)] {
|
||||
for (got, want) in seg.derivatives(t, MAX_DERIVATIVE_ORDER).unwrap().iter().zip(control_derivatives(&pts, at_end, 4)) {
|
||||
assert!(got.dist(want) < 1e-9, "t={t}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seg_derivatives_follow_the_circular_recurrence() {
|
||||
let arc = Seg2::Arc { center: Vec2::new(2.0, -1.0), radius: 5.0, start: 0.7, sweep: -1.9 };
|
||||
let Seg2::Arc { center, sweep, .. } = arc else { panic!("an arc") };
|
||||
for t in [0.0, 0.4, 1.0] {
|
||||
let d = arc.derivatives(t, MAX_DERIVATIVE_ORDER).unwrap();
|
||||
let p = arc.point_at(t);
|
||||
let sw2 = sweep * sweep;
|
||||
// On a circle every derivative follows from the second: P″ = −sw²(P − c), and the rest
|
||||
// differentiate that relation, so a line and an arc have zero curvature rates.
|
||||
assert!(d[1].dist((p - center) * -sw2) < 1e-9, "t={t}");
|
||||
assert!(d[2].dist(d[0] * -sw2) < 1e-9, "t={t}");
|
||||
assert!(d[3].dist(d[1] * -sw2) < 1e-9, "t={t}");
|
||||
assert!(d[0].dist(arc.derivative(t)) < 1e-9, "t={t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seg_derivatives_of_a_conic_satisfy_the_quotient_identity() {
|
||||
let conic = Seg2::Conic { a: Vec2::new(-2.0, 0.0), apex: Vec2::new(0.0, 3.0), b: Vec2::new(4.0, 0.5), w: 0.7 };
|
||||
let Seg2::Conic { a, apex, b, w } = conic else { panic!("a conic") };
|
||||
// The rational quadratic's numerator and weight polynomials, straight from their Bernstein
|
||||
// form, and their power coefficients at `t` by differences (exact for a quadratic).
|
||||
let n_at = |x: f64| a * ((1.0 - x) * (1.0 - x)) + apex * (2.0 * w * x * (1.0 - x)) + b * (x * x);
|
||||
let d_at = |x: f64| (1.0 - x) * (1.0 - x) + 2.0 * w * x * (1.0 - x) + x * x;
|
||||
for t in [0.0, 0.25, 1.0] {
|
||||
let h = 1e-3;
|
||||
// Taylor coefficients at `t` (differences are exact for a quadratic): f, f′/1!, f″/2!.
|
||||
let coef_v = |f: &dyn Fn(f64) -> Vec2| [f(t), (f(t + h) - f(t - h)) / (2.0 * h), (f(t + h) - f(t) * 2.0 + f(t - h)) / (2.0 * h * h)];
|
||||
let coef_s = |f: &dyn Fn(f64) -> f64| [f(t), (f(t + h) - f(t - h)) / (2.0 * h), (f(t + h) - f(t) * 2.0 + f(t - h)) / (2.0 * h * h)];
|
||||
let n = coef_v(&n_at);
|
||||
let d = coef_s(&d_at);
|
||||
let got = conic.derivatives(t, MAX_DERIVATIVE_ORDER).unwrap();
|
||||
// Taylor coefficients of P: P(t) and P⁽ʲ⁾(t)/j!. Leibniz on N = P·D then reads
|
||||
// Σ xᵢ·dⱼ₋ᵢ = nⱼ at every order, which the quotient rule must reproduce.
|
||||
let x: Vec<Vec2> = std::iter::once(conic.point_at(t)).chain(got.iter().enumerate().map(|(i, v)| *v / fact(i + 1))).collect();
|
||||
for j in 0..=4usize {
|
||||
let lhs: Vec2 = (0..=j).fold(Vec2::ZERO, |acc, i| acc + x[i] * d.get(j - i).copied().unwrap_or(0.0));
|
||||
let rhs = n.get(j).copied().unwrap_or(Vec2::ZERO);
|
||||
assert!(lhs.dist(rhs) < 1e-8 * rhs.len().max(1.0), "t={t} j={j}: {lhs:?} vs {rhs:?}");
|
||||
}
|
||||
assert!(got[0].dist(conic.derivative(t)) < 1e-8, "t={t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seg_derivatives_refuse_hostile_input_and_degenerate_pieces() {
|
||||
let c = Seg2::Cubic { p0: Vec2::ZERO, p1: Vec2::X, p2: Vec2::Y, p3: Vec2::X + Vec2::Y };
|
||||
assert!(c.derivatives(0.0, MAX_DERIVATIVE_ORDER + 1).is_none(), "no order above G4");
|
||||
assert!(c.derivatives(f64::NAN, 2).is_none());
|
||||
let nan = Seg2::Line { a: Vec2::new(f64::NAN, 0.0), b: Vec2::X };
|
||||
assert!(nan.derivatives(0.0, 1).is_none());
|
||||
// A conic whose weight vanishes is a straight chord drawn at zero speed: its derivatives
|
||||
// are finite, but the first is zero, which is what a blend refuses.
|
||||
let flat = Seg2::Conic { a: Vec2::ZERO, apex: Vec2::new(1.0, 1.0), b: Vec2::new(2.0, 0.0), w: 0.0 };
|
||||
let d = flat.derivatives(0.0, 1).unwrap();
|
||||
assert_eq!(d[0], Vec2::ZERO);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ use crate::{GpuError, Result, popped};
|
||||
/// The colour format pictures are drawn in: sRGB bytes as they are, like the viewport's usual
|
||||
/// (non-sRGB) target.
|
||||
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8;
|
||||
/// Samples per pixel (MSAA), as the desktop viewport's default; 1 where the device has no 4×.
|
||||
pub const SAMPLES: u32 = 4;
|
||||
/// The largest picture side (pixels); the device's texture limit may lower it.
|
||||
@@ -38,8 +39,6 @@ pub struct Capturer {
|
||||
/// The adapter is a GPU driver running on the CPU (llvmpipe, lavapipe, WARP).
|
||||
software: bool,
|
||||
samples: u32,
|
||||
/// The depth format: 32-bit float (reversed depth) where the device has it ([`crate::depth_format`]).
|
||||
depth: wgpu::TextureFormat,
|
||||
max_side: u32,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
@@ -55,25 +54,17 @@ struct State {
|
||||
impl Capturer {
|
||||
/// The pipelines on an existing device (the application's).
|
||||
pub fn new(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Result<Self> {
|
||||
let depth = crate::depth_format(&device, true);
|
||||
Self::with_depth(adapter, device, queue, depth)
|
||||
}
|
||||
|
||||
/// As [`Capturer::new`], drawing with the depth format `depth` (with a stencil): the fallback
|
||||
/// `Depth24PlusStencil8` on a device that has a float one too, to compare the two.
|
||||
pub fn with_depth(adapter: &wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, depth: wgpu::TextureFormat) -> Result<Self> {
|
||||
let flags = |f: wgpu::TextureFormat| adapter.get_texture_format_features(f).flags;
|
||||
let samples = if flags(FORMAT).sample_count_supported(SAMPLES) && flags(depth).sample_count_supported(SAMPLES) { SAMPLES } else { 1 };
|
||||
let samples = if flags(FORMAT).sample_count_supported(SAMPLES) && flags(DEPTH).sample_count_supported(SAMPLES) { SAMPLES } else { 1 };
|
||||
let scopes = error_scopes(&device);
|
||||
let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(depth), samples, tess: false }, None);
|
||||
let background = background_pipeline(&device, samples, depth);
|
||||
let renderer = Renderer::new(&device, GpuTarget { format: FORMAT, depth: Some(DEPTH), samples, tess: false }, None);
|
||||
let background = background_pipeline(&device, samples);
|
||||
caught(scopes).map_or(Ok(()), |e| Err(GpuError::Pipeline(e)))?;
|
||||
let max_side = device.limits().max_texture_dimension_2d.min(MAX_SIDE);
|
||||
Ok(Capturer {
|
||||
adapter: adapter.get_info().name,
|
||||
software: adapter.get_info().device_type == wgpu::DeviceType::Cpu,
|
||||
samples,
|
||||
depth,
|
||||
max_side,
|
||||
state: Mutex::new(State { renderer, background, key: 0, access_version: 0 }),
|
||||
device,
|
||||
@@ -91,19 +82,6 @@ impl Capturer {
|
||||
Self::new(&adapter, device, queue)
|
||||
}
|
||||
|
||||
/// As [`Capturer::headless`], drawing with the depth format `depth` ([`Capturer::with_depth`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn headless_with_depth(depth: wgpu::TextureFormat) -> Result<Self> {
|
||||
let (adapter, device, queue) = crate::open_headless()?;
|
||||
device.on_uncaptured_error(Arc::new(|e: wgpu::Error| log::error!("GPU: {e}")));
|
||||
Self::with_depth(&adapter, device, queue, depth)
|
||||
}
|
||||
|
||||
/// The depth format pictures are drawn with; float formats are drawn with reversed depth.
|
||||
pub fn depth_format(&self) -> wgpu::TextureFormat {
|
||||
self.depth
|
||||
}
|
||||
|
||||
/// The adapter's name.
|
||||
pub fn adapter_name(&self) -> &str {
|
||||
&self.adapter
|
||||
@@ -154,7 +132,7 @@ impl Capturer {
|
||||
};
|
||||
let resolved = texture("sc_capture", FORMAT, 1, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
|
||||
let multisampled = (self.samples > 1).then(|| texture("sc_capture_ms", FORMAT, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT));
|
||||
let depth = texture("sc_capture_depth", self.depth, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
let depth = texture("sc_capture_depth", DEPTH, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
let (resolved_view, depth_view) = (resolved.create_view(&Default::default()), depth.create_view(&Default::default()));
|
||||
let multisampled_view = multisampled.as_ref().map(|t| t.create_view(&Default::default()));
|
||||
let (top, bottom) = scene.background.unwrap_or(BACKGROUND);
|
||||
@@ -177,10 +155,7 @@ impl Capturer {
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &depth_view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(crate::view::far_depth(crate::view::reversed_depth(Some(self.depth)))),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
|
||||
}),
|
||||
timestamp_writes: None,
|
||||
@@ -412,7 +387,7 @@ fn background_vertices(device: &wgpu::Device, top: Rgb, bottom: Rgb) -> wgpu::Bu
|
||||
})
|
||||
}
|
||||
|
||||
fn background_pipeline(device: &wgpu::Device, samples: u32, depth: wgpu::TextureFormat) -> wgpu::RenderPipeline {
|
||||
fn background_pipeline(device: &wgpu::Device, samples: u32) -> wgpu::RenderPipeline {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("sc_capture_background"),
|
||||
source: wgpu::ShaderSource::Wgsl(BACKGROUND_SHADER.into()),
|
||||
@@ -434,7 +409,7 @@ fn background_pipeline(device: &wgpu::Device, samples: u32, depth: wgpu::Texture
|
||||
},
|
||||
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: depth,
|
||||
format: DEPTH,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(wgpu::CompareFunction::Always),
|
||||
stencil: Default::default(),
|
||||
|
||||
@@ -21,7 +21,6 @@ use wgpu::util::DeviceExt;
|
||||
|
||||
pub mod capture;
|
||||
mod pbr;
|
||||
pub mod pick;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod select;
|
||||
pub mod view;
|
||||
@@ -29,26 +28,6 @@ pub mod view;
|
||||
/// The tessellation compute shader (WGSL).
|
||||
pub const SHADER: &str = include_str!("tess.wgsl");
|
||||
|
||||
/// The device feature for a 32-bit float depth buffer with a stencil, which the viewport draws
|
||||
/// with reversed depth ([`view::reversed_depth`]) where the device has it. A device is opened
|
||||
/// with it whenever its adapter offers it ([`depth_features`]).
|
||||
pub const FLOAT_DEPTH_STENCIL: wgpu::Features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
|
||||
|
||||
/// The depth features to open a device on `adapter` with: [`FLOAT_DEPTH_STENCIL`] if it has it.
|
||||
pub fn depth_features(adapter: &wgpu::Adapter) -> wgpu::Features {
|
||||
adapter.features() & FLOAT_DEPTH_STENCIL
|
||||
}
|
||||
|
||||
/// The depth format to draw with on `device`: 32-bit float (reversed depth) where it can, with a
|
||||
/// stencil when `stencil` (the section cap needs one), else 24 bits with a stencil.
|
||||
pub fn depth_format(device: &wgpu::Device, stencil: bool) -> wgpu::TextureFormat {
|
||||
match (stencil, device.features().contains(FLOAT_DEPTH_STENCIL)) {
|
||||
(false, _) => wgpu::TextureFormat::Depth32Float,
|
||||
(true, true) => wgpu::TextureFormat::Depth32FloatStencil8,
|
||||
(true, false) => wgpu::TextureFormat::Depth24PlusStencil8,
|
||||
}
|
||||
}
|
||||
|
||||
/// The error a popped error scope caught. Native devices answer at once; a browser's answer
|
||||
/// comes later, and is not waited for (no error is assumed).
|
||||
fn popped(f: impl std::future::Future<Output = Option<wgpu::Error>>) -> Option<wgpu::Error> {
|
||||
@@ -68,7 +47,6 @@ fn open_headless() -> Result<(wgpu::Adapter, wgpu::Device, wgpu::Queue)> {
|
||||
let (adapter, _) = select::pick(policy).ok_or(GpuError::NoAdapter(policy.name()))?;
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("solidcraft headless"),
|
||||
required_features: depth_features(&adapter),
|
||||
required_limits: wgpu::Limits::downlevel_defaults().using_resolution(adapter.limits()),
|
||||
..Default::default()
|
||||
}))
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
//! The pick buffer: which model edges are visible at each pixel of the viewport, for picking on a
|
||||
//! large model without testing every edge. Surfaces are drawn into the depth buffer only; then
|
||||
//! every edge segment is drawn as a line carrying its id, depth tested against them (lifted
|
||||
//! toward the eye by the picker's slack, the depth by which an edge may lie behind a face and
|
||||
//! still count as visible) and written into an `R32Uint` id texture (0: no edge).
|
||||
//!
|
||||
//! The pass is drawn once per view (camera, viewport size, model), and only small tiles around
|
||||
//! the cursor are read back, so a pointer moving over a still view reads a few kilobytes and
|
||||
//! draws nothing. Read-backs arrive a frame or two later ([`PickResults`]); until a tile is in,
|
||||
//! the picker answers on the CPU. The ids are hints: the picker still runs its exact tests on
|
||||
//! the edges a tile names.
|
||||
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// The side of a read-back tile, in pixels (a multiple of 64, so rows need no padding).
|
||||
pub const TILE: u32 = 128;
|
||||
/// Most tiles kept from one view.
|
||||
const KEEP: usize = 6;
|
||||
/// Most read-backs in flight.
|
||||
const IN_FLIGHT: usize = 3;
|
||||
/// Bytes per surface vertex (position) and per edge vertex (position, id).
|
||||
const FACE_VERTEX: u64 = 12;
|
||||
const EDGE_VERTEX: u64 = 16;
|
||||
const UNIFORM_SIZE: u64 = 96;
|
||||
|
||||
const SHADER: &str = r#"
|
||||
struct U {
|
||||
vp: mat4x4<f32>,
|
||||
eye: vec4<f32>, // eye position, w = 1 for perspective
|
||||
back: vec4<f32>, // toward the eye (orthographic), w = how far edges are lifted toward it
|
||||
};
|
||||
@group(0) @binding(0) var<uniform> u: U;
|
||||
|
||||
@vertex
|
||||
fn vs_face(@location(0) p: vec3<f32>) -> @builtin(position) vec4<f32> {
|
||||
return u.vp * vec4<f32>(p, 1.0);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_face() -> @location(0) u32 {
|
||||
return 0u;
|
||||
}
|
||||
|
||||
struct EOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@location(0) @interpolate(flat) id: u32,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_edge(@location(0) p: vec3<f32>, @location(1) id: u32) -> EOut {
|
||||
var toward = u.back.xyz;
|
||||
if (u.eye.w > 0.5) {
|
||||
let v = u.eye.xyz - p;
|
||||
let l = length(v);
|
||||
if (l > 0.0) {
|
||||
toward = v / l;
|
||||
}
|
||||
}
|
||||
var o: EOut;
|
||||
o.pos = u.vp * vec4<f32>(p + toward * u.back.w, 1.0);
|
||||
o.id = id;
|
||||
return o;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_edge(i: EOut) -> @location(0) u32 {
|
||||
return i.id;
|
||||
}
|
||||
"#;
|
||||
|
||||
/// What the pass draws: surfaces (for depth) and edge segments with their ids (from 1).
|
||||
#[derive(Default, Clone)]
|
||||
pub struct PickScene {
|
||||
faces: Vec<u8>,
|
||||
edges: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PickScene {
|
||||
pub fn triangle(&mut self, t: [[f32; 3]; 3]) {
|
||||
for p in t {
|
||||
for c in p {
|
||||
self.faces.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Segment `a`–`b` of the edge `id` (0 is no edge: not drawn).
|
||||
pub fn segment(&mut self, a: [f32; 3], b: [f32; 3], id: u32) {
|
||||
if id == 0 {
|
||||
return;
|
||||
}
|
||||
for p in [a, b] {
|
||||
for c in p {
|
||||
self.edges.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
self.edges.extend_from_slice(&id.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.edges.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The view the pass is drawn for.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PickView {
|
||||
/// Changes whenever anything below or the scene changes.
|
||||
pub key: u64,
|
||||
/// Column-major view-projection (as [`crate::view::Frame::view_proj`]).
|
||||
pub view_proj: [[f32; 4]; 4],
|
||||
/// Eye position, and 1 for a perspective camera (0: orthographic).
|
||||
pub eye: [f32; 4],
|
||||
/// Direction toward the eye (orthographic).
|
||||
pub back: [f32; 3],
|
||||
/// How far edges are lifted toward the eye (model units).
|
||||
pub lift: f32,
|
||||
/// The viewport in physical pixels.
|
||||
pub size: [u32; 2],
|
||||
}
|
||||
|
||||
/// Edge ids of a block of pixels of one view.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PickTile {
|
||||
pub key: u64,
|
||||
pub origin: [u32; 2],
|
||||
pub size: [u32; 2],
|
||||
/// Row-major, `size[0] * size[1]`.
|
||||
pub ids: Vec<u32>,
|
||||
}
|
||||
|
||||
impl PickTile {
|
||||
/// Whether the tile is of view `key` and holds every pixel of `[x0, y0, x1, y1]` (inclusive)
|
||||
/// that lies inside a viewport of `view` pixels.
|
||||
pub fn covers(&self, key: u64, view: [u32; 2], [x0, y0, x1, y1]: [i64; 4]) -> bool {
|
||||
let clamp = |v: i64, n: u32| v.clamp(0, i64::from(n.max(1)) - 1);
|
||||
let (x0, x1, y0, y1) = (clamp(x0, view[0]), clamp(x1, view[0]), clamp(y0, view[1]), clamp(y1, view[1]));
|
||||
let [ox, oy] = self.origin.map(i64::from);
|
||||
let [w, h] = self.size.map(i64::from);
|
||||
self.key == key && x0 >= ox && y0 >= oy && x1 < ox + w && y1 < oy + h
|
||||
}
|
||||
|
||||
/// The ids within `[x0, y0, x1, y1]` (inclusive; outside the tile: none), each once.
|
||||
pub fn ids_in(&self, [x0, y0, x1, y1]: [i64; 4]) -> Vec<u32> {
|
||||
let [ox, oy] = self.origin.map(i64::from);
|
||||
let [w, h] = self.size.map(i64::from);
|
||||
let mut out = Vec::new();
|
||||
for y in y0.max(oy)..=y1.min(oy + h - 1) {
|
||||
for x in x0.max(ox)..=x1.min(ox + w - 1) {
|
||||
if let Some(&id) = self.ids.get(((y - oy) * w + (x - ox)) as usize)
|
||||
&& id != 0
|
||||
{
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The tiles read back so far (of the latest view only), newest last.
|
||||
#[derive(Default, Debug)]
|
||||
pub struct PickResults {
|
||||
pub tiles: Vec<PickTile>,
|
||||
}
|
||||
|
||||
impl PickResults {
|
||||
/// The newest tile of view `key` covering `window`.
|
||||
pub fn tile(&self, key: u64, view: [u32; 2], window: [i64; 4]) -> Option<&PickTile> {
|
||||
self.tiles.iter().rev().find(|t| t.covers(key, view, window))
|
||||
}
|
||||
}
|
||||
|
||||
pub type PickOut = Arc<Mutex<PickResults>>;
|
||||
|
||||
/// The tile (origin and size) around pixel `centre` of a viewport of `view` pixels.
|
||||
pub fn tile_around(centre: [u32; 2], view: [u32; 2]) -> ([u32; 2], [u32; 2]) {
|
||||
let size = [TILE.min(view[0]), TILE.min(view[1])];
|
||||
let origin = [0, 1].map(|k| centre[k].saturating_sub(size[k] / 2).min(view[k].saturating_sub(size[k])));
|
||||
(origin, size)
|
||||
}
|
||||
|
||||
const NEW: u8 = 0;
|
||||
const MAPPING: u8 = 1;
|
||||
const READY: u8 = 2;
|
||||
const FAILED: u8 = 3;
|
||||
|
||||
/// A tile being copied out of the id texture.
|
||||
struct Pending {
|
||||
key: u64,
|
||||
origin: [u32; 2],
|
||||
size: [u32; 2],
|
||||
bytes_per_row: u32,
|
||||
buffer: wgpu::Buffer,
|
||||
/// The frame whose commands copy it (it is mapped once they are submitted).
|
||||
frame: u64,
|
||||
state: Arc<AtomicU8>,
|
||||
}
|
||||
|
||||
struct Target {
|
||||
size: [u32; 2],
|
||||
ids: wgpu::Texture,
|
||||
ids_view: wgpu::TextureView,
|
||||
depth_view: wgpu::TextureView,
|
||||
}
|
||||
|
||||
struct Uploaded {
|
||||
key: u64,
|
||||
faces: Option<(wgpu::Buffer, u32)>,
|
||||
edges: Option<(wgpu::Buffer, u32)>,
|
||||
}
|
||||
|
||||
/// The pass's pipelines, its textures and the read-backs in flight, on one device.
|
||||
pub struct PickBuffer {
|
||||
face: wgpu::RenderPipeline,
|
||||
edge: wgpu::RenderPipeline,
|
||||
uniform: wgpu::Buffer,
|
||||
bind: wgpu::BindGroup,
|
||||
scene: Option<Uploaded>,
|
||||
target: Option<Target>,
|
||||
/// The view drawn into the textures.
|
||||
drawn: Option<u64>,
|
||||
pending: Vec<Pending>,
|
||||
frame: u64,
|
||||
}
|
||||
|
||||
const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
|
||||
const IDS: wgpu::TextureFormat = wgpu::TextureFormat::R32Uint;
|
||||
|
||||
impl PickBuffer {
|
||||
pub fn new(device: &wgpu::Device) -> PickBuffer {
|
||||
let module =
|
||||
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_pick"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
|
||||
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("sc_pick"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("sc_pick"),
|
||||
bind_group_layouts: &[Some(&bgl)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("sc_pick_u"),
|
||||
size: UNIFORM_SIZE,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("sc_pick"),
|
||||
layout: &bgl,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }],
|
||||
});
|
||||
const FA: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x3];
|
||||
const EA: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32];
|
||||
let pipeline = |label: &str,
|
||||
vs: &str,
|
||||
fs: &str,
|
||||
stride: u64,
|
||||
attributes: &'static [wgpu::VertexAttribute],
|
||||
topology: wgpu::PrimitiveTopology,
|
||||
write: bool,
|
||||
mask: wgpu::ColorWrites| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some(vs),
|
||||
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: stride, step_mode: wgpu::VertexStepMode::Vertex, attributes })],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
primitive: wgpu::PrimitiveState { topology, ..Default::default() },
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: DEPTH,
|
||||
depth_write_enabled: Some(write),
|
||||
depth_compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some(fs),
|
||||
targets: &[Some(wgpu::ColorTargetState { format: IDS, blend: None, write_mask: mask })],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let face =
|
||||
pipeline("sc_pick_face", "vs_face", "fs_face", FACE_VERTEX, &FA, wgpu::PrimitiveTopology::TriangleList, true, wgpu::ColorWrites::empty());
|
||||
let edge = pipeline("sc_pick_edge", "vs_edge", "fs_edge", EDGE_VERTEX, &EA, wgpu::PrimitiveTopology::LineList, false, wgpu::ColorWrites::ALL);
|
||||
PickBuffer { face, edge, uniform, bind, scene: None, target: None, drawn: None, pending: Vec::new(), frame: 0 }
|
||||
}
|
||||
|
||||
/// Before the frame is submitted: collect the tiles read back, then draw `view` of `scene`
|
||||
/// (`scene_key` names it; it is uploaded when that changes) unless it is drawn already, and
|
||||
/// start reading back the tile around pixel `centre` unless it is in or on its way. The tiles
|
||||
/// land in `out` a frame or two later; keep frames coming until then.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
scene_key: u64,
|
||||
scene: &PickScene,
|
||||
view: &PickView,
|
||||
centre: Option<[u32; 2]>,
|
||||
out: &PickOut,
|
||||
) {
|
||||
self.frame += 1;
|
||||
self.collect(device, out);
|
||||
let [w, h] = view.size;
|
||||
let max = device.limits().max_texture_dimension_2d;
|
||||
if w == 0 || h == 0 || w > max || h > max {
|
||||
return;
|
||||
}
|
||||
if self.scene.as_ref().is_none_or(|s| s.key != scene_key) {
|
||||
let limit = device.limits().max_buffer_size;
|
||||
let upload = |label: &str, bytes: &[u8], stride: u64| {
|
||||
let n = bytes.len() as u64 / stride;
|
||||
(n > 0 && (bytes.len() as u64) <= limit && n <= u64::from(u32::MAX)).then(|| {
|
||||
(
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some(label),
|
||||
contents: bytes,
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
}),
|
||||
n as u32,
|
||||
)
|
||||
})
|
||||
};
|
||||
self.scene = Some(Uploaded {
|
||||
key: scene_key,
|
||||
faces: upload("sc_pick_faces", &scene.faces, FACE_VERTEX),
|
||||
edges: upload("sc_pick_edges", &scene.edges, EDGE_VERTEX),
|
||||
});
|
||||
self.drawn = None;
|
||||
}
|
||||
if self.target.as_ref().is_none_or(|t| t.size != view.size) {
|
||||
let texture = |label: &str, format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
};
|
||||
let ids = texture("sc_pick_ids", IDS, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
|
||||
let depth = texture("sc_pick_depth", DEPTH, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
let (ids_view, depth_view) = (ids.create_view(&Default::default()), depth.create_view(&Default::default()));
|
||||
self.target = Some(Target { size: view.size, ids, ids_view, depth_view });
|
||||
self.drawn = None;
|
||||
}
|
||||
let (Some(target), Some(scene)) = (&self.target, &self.scene) else { return };
|
||||
if self.drawn != Some(view.key) {
|
||||
queue.write_buffer(&self.uniform, 0, &uniform_bytes(view));
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("sc_pick"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &target.ids_view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &target.depth_view,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_bind_group(0, &self.bind, &[]);
|
||||
for (pipeline, part) in [(&self.face, &scene.faces), (&self.edge, &scene.edges)] {
|
||||
if let Some((buffer, n)) = part {
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_vertex_buffer(0, buffer.slice(..));
|
||||
pass.draw(0..*n, 0..1);
|
||||
}
|
||||
}
|
||||
drop(pass);
|
||||
self.drawn = Some(view.key);
|
||||
// Tiles of other views no longer answer.
|
||||
self.pending.retain(|p| p.key == view.key);
|
||||
if let Ok(mut o) = out.lock() {
|
||||
o.tiles.retain(|t| t.key == view.key);
|
||||
}
|
||||
}
|
||||
let Some(centre) = centre else { return };
|
||||
let (origin, size) = tile_around(centre, view.size);
|
||||
let known = out.lock().is_ok_and(|o| o.tiles.iter().any(|t| t.key == view.key && t.origin == origin && t.size == size))
|
||||
|| self.pending.iter().any(|p| p.key == view.key && p.origin == origin && p.size == size);
|
||||
if known || self.pending.len() >= IN_FLIGHT {
|
||||
return;
|
||||
}
|
||||
let bytes_per_row = (size[0] * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("sc_pick_tile"),
|
||||
size: u64::from(bytes_per_row) * u64::from(size[1]),
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &target.ids,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: origin[0], y: origin[1], z: 0 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bytes_per_row), rows_per_image: Some(size[1]) },
|
||||
},
|
||||
wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
|
||||
);
|
||||
self.pending.push(Pending { key: view.key, origin, size, bytes_per_row, buffer, frame: self.frame, state: Arc::new(AtomicU8::new(NEW)) });
|
||||
}
|
||||
|
||||
/// Whether read-backs are still on their way (keep frames coming).
|
||||
pub fn waiting(&self) -> bool {
|
||||
!self.pending.is_empty()
|
||||
}
|
||||
|
||||
/// Maps the copies earlier frames submitted and moves the mapped ones into `out`.
|
||||
fn collect(&mut self, device: &wgpu::Device, out: &PickOut) {
|
||||
let frame = self.frame;
|
||||
for p in &self.pending {
|
||||
if p.frame < frame && p.state.load(Ordering::Acquire) == NEW {
|
||||
p.state.store(MAPPING, Ordering::Release);
|
||||
let state = p.state.clone();
|
||||
p.buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { READY } else { FAILED }, Ordering::Release));
|
||||
}
|
||||
}
|
||||
if self.pending.iter().any(|p| p.state.load(Ordering::Acquire) == MAPPING) {
|
||||
let _ = device.poll(wgpu::PollType::Poll);
|
||||
}
|
||||
let mut done = Vec::new();
|
||||
self.pending.retain(|p| match p.state.load(Ordering::Acquire) {
|
||||
READY => {
|
||||
if let Ok(bytes) = p.buffer.slice(..).get_mapped_range() {
|
||||
let [w, h] = p.size;
|
||||
let mut ids = Vec::with_capacity(w as usize * h as usize);
|
||||
for row in bytes.chunks(p.bytes_per_row as usize).take(h as usize) {
|
||||
ids.extend(row.as_chunks::<4>().0.iter().take(w as usize).map(|c| u32::from_le_bytes(*c)));
|
||||
}
|
||||
done.push(PickTile { key: p.key, origin: p.origin, size: p.size, ids });
|
||||
}
|
||||
p.buffer.unmap();
|
||||
false
|
||||
}
|
||||
FAILED => false,
|
||||
_ => true,
|
||||
});
|
||||
if !done.is_empty()
|
||||
&& let Ok(mut o) = out.lock()
|
||||
{
|
||||
for t in done {
|
||||
if self.drawn == Some(t.key) && t.ids.len() == t.size[0] as usize * t.size[1] as usize {
|
||||
o.tiles.retain(|x| x.key == t.key);
|
||||
o.tiles.push(t);
|
||||
}
|
||||
}
|
||||
let excess = o.tiles.len().saturating_sub(KEEP);
|
||||
o.tiles.drain(..excess);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uniform_bytes(v: &PickView) -> Vec<u8> {
|
||||
let mut b = Vec::with_capacity(UNIFORM_SIZE as usize);
|
||||
for col in v.view_proj {
|
||||
for x in col {
|
||||
b.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
}
|
||||
for x in v.eye.into_iter().chain(v.back).chain([v.lift]) {
|
||||
b.extend_from_slice(&x.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "pick_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,79 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
/// Looking down −z at x, y in −10..10 (orthographic): depth 0 at z = 50, 1 at z = −50.
|
||||
const VIEW: [[f32; 4]; 4] = [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]];
|
||||
const SIZE: u32 = 64;
|
||||
|
||||
/// The pixel of model point (x, y).
|
||||
fn px(x: f32, y: f32) -> [i64; 2] {
|
||||
[((x / 10.0 + 1.0) * 0.5 * SIZE as f32) as i64, ((1.0 - y / 10.0) * 0.5 * SIZE as f32) as i64]
|
||||
}
|
||||
|
||||
/// A square face at z = 0 (x, y in −5..5), and three edges: 1 on it, 2 well behind it, 3 behind
|
||||
/// it by less than the lift.
|
||||
fn scene() -> PickScene {
|
||||
let mut s = PickScene::default();
|
||||
let (a, b, c, d) = ([-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]);
|
||||
s.triangle([a, b, c]);
|
||||
s.triangle([a, c, d]);
|
||||
s.segment([-8.0, 0.0, 0.0], [8.0, 0.0, 0.0], 1);
|
||||
s.segment([2.0, -8.0, -3.0], [2.0, 8.0, -3.0], 2);
|
||||
s.segment([-2.0, -8.0, -0.2], [-2.0, 8.0, -0.2], 3);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pick_buffer_names_the_edges_seen_at_each_pixel() {
|
||||
let (_, device, queue) = match crate::open_headless() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here: {e}");
|
||||
eprintln!("skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut pb = PickBuffer::new(&device);
|
||||
let out = PickOut::default();
|
||||
let view = PickView { key: 7, view_proj: VIEW, eye: [0.0, 0.0, 100.0, 0.0], back: [0.0, 0.0, 1.0], lift: 0.5, size: [SIZE, SIZE] };
|
||||
let scene = scene();
|
||||
let all = [0, 0, SIZE as i64 - 1, SIZE as i64 - 1];
|
||||
for _ in 0..8 {
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
pb.prepare(&device, &queue, &mut encoder, 1, &scene, &view, Some([SIZE / 2, SIZE / 2]), &out);
|
||||
queue.submit([encoder.finish()]);
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
if out.lock().unwrap().tile(7, [SIZE, SIZE], all).is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let results = out.lock().unwrap();
|
||||
let tile = results.tile(7, [SIZE, SIZE], all).expect("the tile is read back within a few frames");
|
||||
let at = |x: f32, y: f32| {
|
||||
let [px, py] = px(x, y);
|
||||
tile.ids_in([px - 1, py - 1, px + 1, py + 1])
|
||||
};
|
||||
assert_eq!(at(0.0, 0.0), vec![1], "the edge on the face");
|
||||
assert_eq!(at(2.0, 3.0), Vec::<u32>::new(), "the edge behind the face is hidden");
|
||||
assert_eq!(at(2.0, 7.5), vec![2], "and seen where the face does not cover it");
|
||||
assert_eq!(at(-2.0, 3.0), vec![3], "an edge behind the face by less than the lift counts as seen");
|
||||
assert_eq!(at(3.5, 3.5), Vec::<u32>::new(), "the face itself names no edge");
|
||||
assert!(results.tile(8, [SIZE, SIZE], all).is_none(), "another view's tile does not answer");
|
||||
drop(results);
|
||||
assert!(!pb.waiting());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_cover_the_window_around_the_cursor_inside_the_view() {
|
||||
assert_eq!(tile_around([10, 10], [1000, 800]), ([0, 0], [TILE, TILE]));
|
||||
assert_eq!(tile_around([500, 400], [1000, 800]), ([500 - TILE / 2, 400 - TILE / 2], [TILE, TILE]));
|
||||
assert_eq!(tile_around([999, 799], [1000, 800]), ([1000 - TILE, 800 - TILE], [TILE, TILE]));
|
||||
assert_eq!(tile_around([30, 20], [50, 40]), ([0, 0], [50, 40]));
|
||||
let t = PickTile { key: 1, origin: [100, 100], size: [TILE, TILE], ids: vec![0; (TILE * TILE) as usize] };
|
||||
assert!(t.covers(1, [1000, 800], [110, 110, 120, 120]));
|
||||
assert!(!t.covers(1, [1000, 800], [90, 110, 120, 120]));
|
||||
assert!(!t.covers(2, [1000, 800], [110, 110, 120, 120]));
|
||||
// A window past the view's border needs only the pixels inside it.
|
||||
let corner = PickTile { key: 1, origin: [0, 0], size: [TILE, TILE], ids: vec![5; (TILE * TILE) as usize] };
|
||||
assert!(corner.covers(1, [1000, 800], [-8, -8, 8, 8]));
|
||||
assert_eq!(corner.ids_in([-8, -8, 8, 8]), vec![5]);
|
||||
}
|
||||
+18
-155
@@ -19,9 +19,9 @@ pub const TRI_SIZE: usize = 28;
|
||||
pub const PBR_SIZE: usize = pbr::VERTEX_SIZE;
|
||||
/// Line instance: a, b (3 × f32 each), colour (4 × u8), width in pixels (f32).
|
||||
pub const LINE_SIZE: usize = 32;
|
||||
/// The shader's `U`: the view-projection matrix, 9 `vec4`s, the 8 analysis colours, their
|
||||
/// flags and the depth direction (`uniform_bytes`).
|
||||
const UNIFORM_SIZE: u64 = 368;
|
||||
/// The shader's `U`: the view-projection matrix, 9 `vec4`s, the 8 analysis colours and their
|
||||
/// flags (`uniform_bytes`).
|
||||
const UNIFORM_SIZE: u64 = 352;
|
||||
|
||||
/// A body drawn from its display plan, evaluated on the GPU: the plan, and a colour per face
|
||||
/// (the plan's face numbering; faces past the end take the last colour).
|
||||
@@ -599,26 +599,8 @@ pub struct Renderer {
|
||||
ss: Option<Supersampled>,
|
||||
/// This frame was drawn supersampled (in `prepare`): `paint` only filters it down.
|
||||
ss_ready: bool,
|
||||
/// 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<wgpu::RenderPipeline>,
|
||||
}
|
||||
|
||||
/// A triangle over the whole viewport at depth 0 (the far plane of reversed depth), writing no
|
||||
/// colour: [`Renderer::depth_reset`].
|
||||
const DEPTH_RESET_SHADER: &str = r#"
|
||||
@vertex
|
||||
fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
let x = f32((i << 1u) & 2u);
|
||||
let y = f32(i & 2u);
|
||||
return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
@fragment
|
||||
fn fs() -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// A supersampled frame: the scene drawn at a multiple of the viewport's pixels.
|
||||
struct Supersampled {
|
||||
size: [u32; 2],
|
||||
@@ -753,55 +735,6 @@ pub struct GpuTarget {
|
||||
pub tess: bool,
|
||||
}
|
||||
|
||||
impl GpuTarget {
|
||||
/// Depth runs from 1 at the near plane to 0 at the far one: see [`reversed_depth`].
|
||||
pub fn reversed_depth(&self) -> bool {
|
||||
reversed_depth(self.depth)
|
||||
}
|
||||
}
|
||||
|
||||
/// Is depth reversed (1 at the near plane, 0 at the far one) in a buffer of `format`? It is with a
|
||||
/// 32-bit float buffer: a float's steps grow with its value, so with depth falling away from the
|
||||
/// eye they follow the distance, about 2⁻²⁴ of it everywhere, instead of piling up at the near
|
||||
/// plane (#1434: a face 0.3 mm in front of another speckled at 10 m). Other formats keep 0 near.
|
||||
pub fn reversed_depth(format: Option<wgpu::TextureFormat>) -> bool {
|
||||
matches!(format, Some(wgpu::TextureFormat::Depth32Float | wgpu::TextureFormat::Depth32FloatStencil8))
|
||||
}
|
||||
|
||||
/// The depth test `compare`, written for depth growing away from the eye, for a buffer whose depth
|
||||
/// may run the other way ([`reversed_depth`]). Every pass drawn with the viewport's depth takes
|
||||
/// its tests from here, so it agrees with the viewport whichever way depth runs.
|
||||
pub fn depth_compare(reversed: bool, compare: wgpu::CompareFunction) -> wgpu::CompareFunction {
|
||||
use wgpu::CompareFunction::{Greater, GreaterEqual, Less, LessEqual};
|
||||
match compare {
|
||||
Less if reversed => Greater,
|
||||
LessEqual if reversed => GreaterEqual,
|
||||
Greater if reversed => Less,
|
||||
GreaterEqual if reversed => LessEqual,
|
||||
c => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// A depth bias written for depth growing away from the eye (negative: toward it), turned round
|
||||
/// for reversed depth.
|
||||
pub fn depth_bias(reversed: bool, b: wgpu::DepthBiasState) -> wgpu::DepthBiasState {
|
||||
if reversed { wgpu::DepthBiasState { constant: -b.constant, slope_scale: -b.slope_scale, clamp: -b.clamp } } else { b }
|
||||
}
|
||||
|
||||
/// The depth of the far plane, which a depth buffer is cleared to.
|
||||
pub fn far_depth(reversed: bool) -> f32 {
|
||||
if reversed { 0.0 } else { 1.0 }
|
||||
}
|
||||
|
||||
/// The view-projection the GPU draws with: `vp` (depth 0 near, 1 far, as the CPU uses it), with
|
||||
/// depth turned round (z' = w - z) for reversed depth. Columns, as `Mat4::to_f32` gives them.
|
||||
pub fn gpu_view_proj(vp: [[f32; 4]; 4], reversed: bool) -> [[f32; 4]; 4] {
|
||||
if !reversed {
|
||||
return vp;
|
||||
}
|
||||
vp.map(|c| [c[0], c[1], c[3] - c[2], c[3]])
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// The pipelines for target `t` on `device`; `tess` evaluates planned bodies on the GPU.
|
||||
pub fn new(device: &wgpu::Device, t: GpuTarget, tess: Option<crate::TessGpu>) -> Self {
|
||||
@@ -833,20 +766,15 @@ impl Renderer {
|
||||
layout: &bgl,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }],
|
||||
});
|
||||
let reversed = t.reversed_depth();
|
||||
let depth = |compare: wgpu::CompareFunction, write: bool| -> Option<wgpu::DepthStencilState> {
|
||||
t.depth.map(|format| wgpu::DepthStencilState {
|
||||
format,
|
||||
depth_write_enabled: Some(write),
|
||||
depth_compare: Some(depth_compare(reversed, compare)),
|
||||
depth_compare: Some(compare),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
})
|
||||
};
|
||||
// Opaque faces pushed back by their own slope (FACE_BIAS); ghosts twice as far.
|
||||
let pushed = |compare: wgpu::CompareFunction, write: bool, bias: wgpu::DepthBiasState| -> Option<wgpu::DepthStencilState> {
|
||||
depth(compare, write).map(|d| wgpu::DepthStencilState { bias: depth_bias(reversed, bias), ..d })
|
||||
};
|
||||
let pipeline = |label: &str,
|
||||
vs: &str,
|
||||
fs: &str,
|
||||
@@ -998,9 +926,9 @@ impl Renderer {
|
||||
let mark = wgpu::DepthStencilState {
|
||||
format,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),
|
||||
depth_compare: Some(wgpu::CompareFunction::Less),
|
||||
stencil: wgpu::StencilState { front: face(Zero), back: face(Replace), read_mask: 0xff, write_mask: 0xff },
|
||||
bias: depth_bias(reversed, FACE_BIAS),
|
||||
bias: Default::default(),
|
||||
};
|
||||
// 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) };
|
||||
@@ -1074,41 +1002,7 @@ impl Renderer {
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let depth_reset = t.depth.filter(|_| reversed).map(|format| {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("sc_depth_reset"),
|
||||
source: wgpu::ShaderSource::Wgsl(DEPTH_RESET_SHADER.into()),
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("sc_depth_reset"),
|
||||
bind_group_layouts: &[],
|
||||
immediate_size: 0,
|
||||
});
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("sc_depth_reset"),
|
||||
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(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState { count: t.samples.max(1), mask: !0, alpha_to_coverage_enabled: false },
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs"),
|
||||
targets: &[Some(wgpu::ColorTargetState { format: t.format, blend: None, write_mask: wgpu::ColorWrites::empty() })],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
});
|
||||
Renderer {
|
||||
depth_reset,
|
||||
target: t,
|
||||
max_texture: device.limits().max_texture_dimension_2d,
|
||||
ss_blit,
|
||||
@@ -1120,20 +1014,20 @@ impl Renderer {
|
||||
sampler,
|
||||
textures: Default::default(),
|
||||
quads: Vec::new(),
|
||||
tri: solid("sc_tris", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), false),
|
||||
tri: solid("sc_tris", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), false),
|
||||
tri_cut: cut(false),
|
||||
tri_planned: solid("sc_tris_planned", "fs_solid", None, pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), true),
|
||||
tri_planned: solid("sc_tris_planned", "fs_solid", None, depth(wgpu::CompareFunction::Less, true), true),
|
||||
tri_cut_planned: cut(true),
|
||||
tess,
|
||||
access_bgl,
|
||||
access_bind,
|
||||
access_version: 0,
|
||||
tri_hl: pipeline("sc_tris_hl", "vs_tri", "fs_tri", tri_layout(), highlight_depth(t.depth), alpha),
|
||||
pbr: pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), pushed(wgpu::CompareFunction::Less, true, FACE_BIAS), None),
|
||||
pbr: pipeline("sc_pbr", "vs_pbr", "fs_pbr", pbr_layout(), depth(wgpu::CompareFunction::Less, true), None),
|
||||
trans: pipeline("sc_trans", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),
|
||||
glass_far: glass("sc_glass_far", wgpu::Face::Front),
|
||||
glass_near: glass("sc_glass_near", wgpu::Face::Back),
|
||||
ghost: pipeline("sc_ghost", "vs_tri", "fs_tri", tri_layout(), pushed(wgpu::CompareFunction::LessEqual, false, GHOST_BIAS), alpha),
|
||||
ghost: pipeline("sc_ghost", "vs_ghost", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),
|
||||
xray: pipeline("sc_xray", "vs_tri", "fs_tri", tri_layout(), depth(wgpu::CompareFunction::Always, false), alpha),
|
||||
line: pipeline("sc_lines", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::LessEqual, false), alpha),
|
||||
line_hidden: pipeline("sc_lines_hidden", "vs_line", "fs_line", line_layout(), depth(wgpu::CompareFunction::Greater, false), alpha),
|
||||
@@ -1159,40 +1053,18 @@ impl Renderer {
|
||||
/// depths differ by rounding and an unbiased equal test lights the face in speckles and wedges.
|
||||
/// The bias is a few depth steps plus the face's own slope: far less than any real gap.
|
||||
fn highlight_depth(format: Option<wgpu::TextureFormat>) -> Option<wgpu::DepthStencilState> {
|
||||
let reversed = reversed_depth(format);
|
||||
format.map(|format| wgpu::DepthStencilState {
|
||||
format,
|
||||
depth_write_enabled: Some(false),
|
||||
depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::LessEqual)),
|
||||
depth_compare: Some(wgpu::CompareFunction::LessEqual),
|
||||
stencil: Default::default(),
|
||||
bias: depth_bias(reversed, HIGHLIGHT_BIAS),
|
||||
bias: HIGHLIGHT_BIAS,
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`highlight_depth`]. Negative: toward the eye (depth grows away from it).
|
||||
const HIGHLIGHT_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: -8, slope_scale: -1.0, clamp: 0.0 };
|
||||
|
||||
/// Opaque faces are drawn pushed back from the eye by a few depth steps and by their own depth
|
||||
/// slope over [`FACE_SLOPE`] pixels, so whatever lies on a face (its edges, an origin plane, a
|
||||
/// sketch, a decal) is drawn over it at any angle, and an edge behind it stays hidden however
|
||||
/// large the scene (#1434, #1739). The CPU renderer has the same rule (`raster.rs`, #983).
|
||||
/// Lines used to be pulled toward the eye by a share of the depth range instead, which on a large
|
||||
/// design reached tens of millimetres. Positive: away from the eye.
|
||||
pub const FACE_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: FACE_STEPS, slope_scale: FACE_SLOPE, clamp: 0.0 };
|
||||
/// The depth steps of [`FACE_BIAS`]: f32 rounding between a face and what lies on it (the GPU
|
||||
/// evaluates planned bodies in f32; edges and overlays come from the CPU).
|
||||
pub const FACE_STEPS: i32 = 8;
|
||||
/// The pixels of [`FACE_BIAS`]: half a 2 px line, so edges (1.2 px) draw whole on a steep face.
|
||||
/// It is also how far behind a face an edge may show, in that face's own depth per pixel: at 10 m
|
||||
/// a pixel is about 9 mm, and a face turned 25° gains 4 mm of depth across it, so a larger value
|
||||
/// let a washer 12 mm behind a plate show through it (#1434). A thicker line (a selected edge,
|
||||
/// 3.5 px) may lose its outer edge on one side where it lies on a steep face. The section cap,
|
||||
/// which writes its own depth, adds the same in the shader.
|
||||
pub const FACE_SLOPE: f32 = 1.0;
|
||||
/// The removed material of a preview, drawn translucent: behind the faces it shares with the new
|
||||
/// shape, so twice [`FACE_BIAS`].
|
||||
const GHOST_BIAS: wgpu::DepthBiasState = wgpu::DepthBiasState { constant: 2 * FACE_STEPS, slope_scale: 2.0 * FACE_SLOPE, clamp: 0.0 };
|
||||
|
||||
fn upload(device: &wgpu::Device, label: &str, bytes: &[u8], stride: usize) -> Option<Batch> {
|
||||
upload_with(device, label, bytes, stride, wgpu::BufferUsages::VERTEX)
|
||||
}
|
||||
@@ -1290,7 +1162,7 @@ impl Renderer {
|
||||
if cb.product {
|
||||
res.product.take(device, cb.key, &cb.slot, None);
|
||||
res.product.sort_glass(queue, cb.back);
|
||||
queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out, res.target.reversed_depth()));
|
||||
queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out));
|
||||
return;
|
||||
}
|
||||
res.model.take(device, cb.key, &cb.slot, res.tess.as_ref().map(|t| (t, &mut *encoder)));
|
||||
@@ -1298,7 +1170,7 @@ impl Renderer {
|
||||
res.highlight.take(device, cb.hl_key, &cb.hl_slot, None);
|
||||
res.preview.take(device, cb.pv_key, &cb.pv_slot, None);
|
||||
res.model.sort_glass(queue, cb.back);
|
||||
queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out, res.target.reversed_depth()));
|
||||
queue.write_buffer(&res.uniform, 0, &uniform_bytes(cb, cb.size_px[0], cb.size_px[1], res.linear_out));
|
||||
if let Some(a) = &cb.access
|
||||
&& a.version != res.access_version
|
||||
{
|
||||
@@ -1373,10 +1245,6 @@ impl Renderer {
|
||||
pass.draw(0..3, 0..1);
|
||||
return;
|
||||
}
|
||||
if let Some(reset) = &self.depth_reset {
|
||||
pass.set_pipeline(reset);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
self.draw(frame, pass);
|
||||
}
|
||||
|
||||
@@ -1467,7 +1335,6 @@ impl Renderer {
|
||||
tris(pass, &res.trans, &h.trans);
|
||||
tris(pass, &res.guide_trans, &h.guide_trans);
|
||||
tris(pass, &res.xray, &pv.xray);
|
||||
tris(pass, &res.xray, &h.xray);
|
||||
lines(pass, &res.overlay, &m.overlays);
|
||||
lines(pass, &res.overlay, &sk.overlays);
|
||||
lines(pass, &res.overlay, &h.overlays);
|
||||
@@ -1499,10 +1366,7 @@ impl Renderer {
|
||||
})],
|
||||
depth_stencil_attachment: ss.depth.as_ref().map(|view| wgpu::RenderPassDepthStencilAttachment {
|
||||
view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(far_depth(self.target.reversed_depth())),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: depth_format
|
||||
.filter(|f| f.has_stencil_aspect())
|
||||
.map(|_| wgpu::Operations { load: wgpu::LoadOp::Clear(0), store: wgpu::StoreOp::Discard }),
|
||||
@@ -1555,10 +1419,10 @@ impl Renderer {
|
||||
}
|
||||
|
||||
/// Uniform bytes for a frame.
|
||||
pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) -> Vec<u8> {
|
||||
let mut v: Vec<f32> = gpu_view_proj(cb.view_proj, reversed).iter().flatten().copied().collect();
|
||||
pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool) -> Vec<u8> {
|
||||
let mut v: Vec<f32> = cb.view_proj.iter().flatten().copied().collect();
|
||||
v.extend([cb.back[0], cb.back[1], cb.back[2], if linear { 1.0 } else { 0.0 }]);
|
||||
v.extend([w.max(1.0), h.max(1.0), 0.0, if cb.outline { 1.0 } else { 0.0 }]);
|
||||
v.extend([w.max(1.0), h.max(1.0), 2e-4, if cb.outline { 1.0 } else { 0.0 }]);
|
||||
v.extend(cb.clip);
|
||||
v.extend(cb.cap);
|
||||
v.extend(cb.analysis);
|
||||
@@ -1571,7 +1435,6 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) -
|
||||
}
|
||||
v.extend(cb.eye);
|
||||
v.extend(cb.analysis_colors);
|
||||
v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]);
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
//! Depth in headless pictures, drawn with the viewport's pipelines (#1434, #1739): an edge behind
|
||||
//! a face stays hidden however large the design and however far the camera, and whatever lies on
|
||||
//! a face (its edges, a thin label) draws over it at any angle. Each check runs with the depth the
|
||||
//! device draws with (a 32-bit float buffer, reversed, where it has one) and with the 24-bit
|
||||
//! fallback. Skipped, with the reason printed, without a GPU adapter (`SOLIDCRAFT_REQUIRE_GPU=1`
|
||||
//! makes that a failure).
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::Session;
|
||||
use solidcraft_engine::geom::{Mesh, Vec3};
|
||||
use solidcraft_engine::render::{Camera, Rgb, Scene, SceneLine, SceneMesh, StandardView};
|
||||
use solidcraft_engine::view::{self, Guides};
|
||||
use solidcraft_gpu::GpuError;
|
||||
use solidcraft_gpu::capture::{self, Capturer};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
fn or_skip(c: Result<&'static Capturer, &'static GpuError>) -> Option<&'static Capturer> {
|
||||
match c {
|
||||
Ok(c) => Some(c),
|
||||
Err(e @ GpuError::NoAdapter(_)) if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none() => {
|
||||
eprintln!("skipping: {e}");
|
||||
None
|
||||
}
|
||||
Err(e) => panic!("{e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's own depth, then the 24-bit fallback (the same device kind, its own instance).
|
||||
fn capturers() -> Vec<(&'static str, &'static Capturer)> {
|
||||
static FALLBACK: OnceLock<solidcraft_gpu::Result<Capturer>> = OnceLock::new();
|
||||
let Some(own) = or_skip(capture::shared()) else { return Vec::new() };
|
||||
let Some(fallback) = or_skip(FALLBACK.get_or_init(|| Capturer::headless_with_depth(wgpu::TextureFormat::Depth24PlusStencil8)).as_ref()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
eprintln!("GPU: {}, depth {:?} and {:?}", own.adapter_name(), own.depth_format(), fallback.depth_format());
|
||||
vec![("own", own), ("24-bit", fallback)]
|
||||
}
|
||||
|
||||
fn reversed(c: &Capturer) -> bool {
|
||||
solidcraft_gpu::view::reversed_depth(Some(c.depth_format()))
|
||||
}
|
||||
|
||||
/// RGBA pixels as `[r, g, b, a]`.
|
||||
fn pixels(img: &[u8]) -> impl Iterator<Item = [u8; 4]> + '_ {
|
||||
img.as_chunks::<4>().0.iter().copied()
|
||||
}
|
||||
|
||||
fn red(p: [u8; 4]) -> bool {
|
||||
p[0] > 150 && p[1] < 90 && p[2] < 90
|
||||
}
|
||||
|
||||
fn session(script: &[(&str, serde_json::Value)]) -> Session {
|
||||
let mut s = Session::default();
|
||||
for (c, p) in script {
|
||||
s.execute(c, p).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn picture(c: &Capturer, s: &Session, cam: &Camera, w: u32, h: u32) -> Vec<u8> {
|
||||
c.rgba(&view::scene_with_guides(s, cam, None, Guides { grid: false, axes: false }), cam, w, h).unwrap()
|
||||
}
|
||||
|
||||
fn differing(a: &[u8], b: &[u8]) -> usize {
|
||||
pixels(a).zip(pixels(b)).filter(|(p, q)| p.iter().zip(q).any(|(x, y)| x.abs_diff(*y) > 24)).count()
|
||||
}
|
||||
|
||||
/// The reproduction of #1434: a 20 mm plate with a washer 22–25 mm behind its front face, and a
|
||||
/// 30 m slab far away that makes the design 34 m across. The washer never shows: the picture is
|
||||
/// the same without it. (Lines were pulled toward the eye by 2e-4 of the depth range, about
|
||||
/// 27 mm here in orthographic.)
|
||||
#[test]
|
||||
fn a_washer_behind_a_plate_stays_hidden_on_a_large_design() {
|
||||
let plate = [
|
||||
("solid.box", json!({"length": 30000, "width": 8000, "height": 100, "corner": [-15000, 3000, -3000], "body_name": "slab"})),
|
||||
("solid.box", json!({"length": 200, "width": 20, "height": 200, "corner": [0, 0, 0], "body_name": "plate"})),
|
||||
("solid.cylinder", json!({"radius": 8, "height": 60, "base": [100, -20, 100], "axis": "Y", "body_name": "bolt"})),
|
||||
];
|
||||
let washer = ("solid.cylinder", json!({"radius": 15, "height": 3, "base": [100, 22, 100], "axis": "Y", "body_name": "washer"}));
|
||||
let without = session(&plate);
|
||||
let with = session(&[plate[0].clone(), plate[1].clone(), plate[2].clone(), washer]);
|
||||
for (mode, c) in capturers() {
|
||||
for fov in [0.0, 0.6] {
|
||||
let cam = Camera { target: Vec3::new(100.0, 10.0, 100.0), yaw: 0.35, pitch: 0.25, roll: 0.0, distance: 450.0, fov, ..Default::default() };
|
||||
let n = differing(&picture(c, &with, &cam, 400, 300), &picture(c, &without, &cam, 400, 300));
|
||||
assert_eq!(n, 0, "{mode} depth, fov {fov}: the washer shows through the plate in {n} pixels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #1434's second reproduction, in perspective at 10 m: a 2 m plate, a 600 mm washer 12–15 mm
|
||||
/// behind its front face, and a red label 0.3 mm thick on it. The washer stays hidden in both
|
||||
/// depths; with reversed float depth the label is red all over (in 24 bits one depth step there
|
||||
/// is about 0.6 mm, so the label speckled).
|
||||
#[test]
|
||||
fn at_ten_metres_a_thin_label_is_whole_and_a_washer_behind_stays_hidden() {
|
||||
let base = [
|
||||
("solid.box", json!({"length": 2000, "width": 10, "height": 2000, "corner": [0, 0, 0], "body_name": "plate"})),
|
||||
("solid.box", json!({"length": 1000, "width": 0.3, "height": 400, "corner": [500, -0.3, 1400], "body_name": "label"})),
|
||||
("appearance.assign", json!({"bodies": ["label"], "color": [204, 34, 34]})),
|
||||
];
|
||||
let washer = ("solid.cylinder", json!({"radius": 300, "height": 3, "base": [1000, 12, 1000], "axis": "Y", "body_name": "washer"}));
|
||||
let without = session(&base);
|
||||
let with = session(&[base[0].clone(), base[1].clone(), base[2].clone(), washer]);
|
||||
let cam =
|
||||
Camera { target: Vec3::new(1000.0, 5.0, 1000.0), yaw: 0.35, pitch: 0.25, roll: 0.0, distance: 10_000.0, fov: 0.6, ..Default::default() };
|
||||
let (w, h) = (800, 600);
|
||||
for (mode, c) in capturers() {
|
||||
let img = picture(c, &with, &cam, w, h);
|
||||
let n = differing(&img, &picture(c, &without, &cam, w, h));
|
||||
assert_eq!(n, 0, "{mode} depth: the washer shows through the plate in {n} pixels");
|
||||
if !reversed(c) {
|
||||
continue;
|
||||
}
|
||||
// The label's front face (y = -0.3), sampled inside its outline.
|
||||
let radius = view::scene(&with, &cam).radius;
|
||||
let mut grey = Vec::new();
|
||||
for i in 1..20 {
|
||||
for j in 1..20 {
|
||||
let p = Vec3::new(500.0 + 1000.0 * f64::from(i) / 20.0, -0.3, 1400.0 + 400.0 * f64::from(j) / 20.0);
|
||||
let Some((x, y, _)) = cam.to_screen(p, f64::from(w), f64::from(h), radius) else { continue };
|
||||
let at = (y as usize * w as usize + x as usize) * 4;
|
||||
if let Some(px) = img.get(at..at + 4).and_then(|p| <[u8; 4]>::try_from(p).ok())
|
||||
&& !red(px)
|
||||
{
|
||||
grey.push((x as u32, y as u32, px));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(grey.is_empty(), "{mode} depth: the label speckles at {} of 361 points: {:?}", grey.len(), &grey[..grey.len().min(5)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 30 × 40 mm sheet at y = z·tan(`tilt`) (facing the front camera when `tilt` is 0).
|
||||
fn sheet(tilt: f64) -> Mesh {
|
||||
let t = tilt.tan();
|
||||
let c = [(-15.0, -20.0), (15.0, -20.0), (15.0, 20.0), (-15.0, 20.0)].map(|(x, z)| Vec3::new(x, z * t, z));
|
||||
Mesh {
|
||||
positions: c.to_vec(),
|
||||
normals: vec![Vec3::new(0.0, -tilt.cos(), tilt.sin()); 4],
|
||||
triangles: vec![[0, 1, 2], [0, 2, 3]],
|
||||
tri_face: vec![0, 0],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A front view of `mesh` with `lines`, as part of a design of `radius`, 40 mm high on 200 px.
|
||||
fn front(mesh: Mesh, lines: Vec<SceneLine>, radius: f64, fov: f64) -> (Scene, Camera) {
|
||||
let scene = Scene {
|
||||
meshes: vec![SceneMesh { mesh: Arc::new(mesh), color: Rgb(160, 165, 175), face_colors: Vec::new() }],
|
||||
lines,
|
||||
radius,
|
||||
..Default::default()
|
||||
};
|
||||
let mut cam = Camera { distance: if fov > 0.0 { 25.0 / (fov * 0.5).tan() } else { 62.5 }, fov, ..Default::default() };
|
||||
cam.set_view(StandardView::Front);
|
||||
(scene, cam)
|
||||
}
|
||||
|
||||
fn red_line(a: Vec3, b: Vec3, on_top: bool) -> SceneLine {
|
||||
SceneLine { points: vec![a, b], color: Rgb(255, 0, 0), width: 1.2, on_top }
|
||||
}
|
||||
|
||||
fn red_pixels(c: &Capturer, scene: &Scene, cam: &Camera) -> usize {
|
||||
pixels(&c.rgba(scene, cam, 200, 200).unwrap()).filter(|p| red(*p)).count()
|
||||
}
|
||||
|
||||
/// An edge lying on a face draws its whole width over it, on a face seen square and on one turned
|
||||
/// to 80°, in orthographic and perspective, in a small design and a large one.
|
||||
#[test]
|
||||
fn an_edge_on_a_face_draws_whole_at_any_angle() {
|
||||
for (mode, c) in capturers() {
|
||||
for tilt in [0.0_f64, 60.0, 80.0] {
|
||||
let t = tilt.to_radians().tan();
|
||||
// Across the sheet, at z = 5: y = 5·tan(tilt).
|
||||
let (a, b) = (Vec3::new(-12.0, 5.0 * t, 5.0), Vec3::new(12.0, 5.0 * t, 5.0));
|
||||
for radius in [30.0, 17_000.0] {
|
||||
for fov in [0.0, 0.6] {
|
||||
let (on, cam) = front(sheet(tilt.to_radians()), vec![red_line(a, b, false)], radius, fov);
|
||||
let (top, _) = front(sheet(tilt.to_radians()), vec![red_line(a, b, true)], radius, fov);
|
||||
let (shown, all) = (red_pixels(c, &on, &cam), red_pixels(c, &top, &cam));
|
||||
assert!(all > 50, "{mode}: the line itself ({all} px)");
|
||||
assert!(shown * 10 >= all * 9, "{mode} depth, tilt {tilt}°, radius {radius}, fov {fov}: {shown} of {all} px drawn");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An edge 0.5 mm behind a face seen square is hidden, however large the design: lines were pulled
|
||||
/// toward the eye by a share of the depth range, about 27 mm in a design 34 m across.
|
||||
#[test]
|
||||
fn an_edge_just_behind_a_face_stays_hidden_on_a_large_design() {
|
||||
for (mode, c) in capturers() {
|
||||
for radius in [30.0, 17_000.0] {
|
||||
for fov in [0.0, 0.6] {
|
||||
// The sheet is at y = 0; the camera looks along +y, so behind is +y.
|
||||
let (a, b) = (Vec3::new(-12.0, 0.5, 5.0), Vec3::new(12.0, 0.5, 5.0));
|
||||
let (scene, cam) = front(sheet(0.0), vec![red_line(a, b, false)], radius, fov);
|
||||
let n = red_pixels(c, &scene, &cam);
|
||||
assert_eq!(n, 0, "{mode} depth, radius {radius}, fov {fov}: the edge behind shows in {n} px");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The application's device draws with reversed float depth where it can: every desktop backend
|
||||
/// this runs on (D3D12, Vulkan, Metal) has `Depth32FloatStencil8`.
|
||||
#[test]
|
||||
fn the_device_draws_with_float_depth_where_it_has_it() {
|
||||
let Some(c) = or_skip(capture::shared()) else { return };
|
||||
eprintln!("GPU: {}, depth {:?}", c.adapter_name(), c.depth_format());
|
||||
let float = c.depth_format() == wgpu::TextureFormat::Depth32FloatStencil8;
|
||||
assert_eq!(float, reversed(c));
|
||||
if std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_some() {
|
||||
assert!(float, "a desktop GPU without Depth32FloatStencil8: {:?}", c.depth_format());
|
||||
}
|
||||
}
|
||||
|
||||
/// What lies on a section's cut face draws over the cap, which writes its own depth (so the GPU's
|
||||
/// push does not apply to it; the shader pushes it the same way).
|
||||
#[test]
|
||||
fn an_edge_on_the_cut_face_draws_over_the_cap() {
|
||||
let mut s = session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]);
|
||||
// Cut away the front (y < 15), so the iso camera looks at the cut face at y = 15.
|
||||
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);
|
||||
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);
|
||||
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()
|
||||
};
|
||||
let (shown, all) = (count(false), count(true));
|
||||
assert!(all > 50, "{mode}: the line itself ({all} px)");
|
||||
assert!(shown * 10 >= all * 9, "{mode} depth, fov {fov}: {shown} of {all} px drawn over the cap");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -667,7 +667,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; 8];
|
||||
for (i, s) in q.iter_mut().enumerate() {
|
||||
*s = Vec2::new(i as f64, (i * i) as f64);
|
||||
}
|
||||
|
||||
@@ -864,7 +864,6 @@ mod tests {
|
||||
body: None,
|
||||
style: Default::default(),
|
||||
fit: Default::default(),
|
||||
corner: Default::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -949,7 +948,6 @@ mod tests {
|
||||
body: None,
|
||||
style: Default::default(),
|
||||
fit: Default::default(),
|
||||
corner: Default::default(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -50,11 +50,6 @@ mod imp {
|
||||
check(path)?;
|
||||
std::fs::remove_file(path)
|
||||
}
|
||||
/// A folder and the folders above it, where missing.
|
||||
pub fn create_dir_all(path: &str) -> Result<()> {
|
||||
check(path)?;
|
||||
std::fs::create_dir_all(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -99,10 +94,6 @@ mod imp {
|
||||
pub fn remove(path: &str) -> Result<()> {
|
||||
FILES.with(|f| f.borrow_mut().remove(path)).map(|_| ()).ok_or_else(|| missing(path))
|
||||
}
|
||||
/// Files are keyed by their whole path here: a folder needs no making.
|
||||
pub fn create_dir_all(_path: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
pub fn insert(path: &str, bytes: Vec<u8>) {
|
||||
FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
|
||||
}
|
||||
|
||||
@@ -1637,7 +1637,7 @@ fn lies_on(e: &mt::Edge, along: &[mt::Edge], tol: f64) -> bool {
|
||||
}
|
||||
|
||||
/// [`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<Vec<mt::EdgeID>> {
|
||||
fn smooth_chain_within(solid: &Solid, edge: &mt::Edge, keep: &dyn Fn(&mt::Edge) -> bool) -> Option<Vec<mt::EdgeID>> {
|
||||
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).
|
||||
@@ -1859,7 +1859,7 @@ fn fillet_built(body: &Body, edges: &[Vec3], radius: f64) -> Result<Body> {
|
||||
// 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)))
|
||||
.or_else(|e| corners(body, edges, radius, Shape::Round, "fillet").and_then(|b| closed(body, b)).map_err(|e2| keep_size(e, e2)))
|
||||
}
|
||||
|
||||
/// The first refusal, unless only the second found the blend too large (a smaller one may fit).
|
||||
@@ -1872,9 +1872,8 @@ fn keep_size(e: KernelError, e2: KernelError) -> KernelError {
|
||||
}
|
||||
|
||||
/// 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<Body> {
|
||||
/// (see [`crate::curveblend::corner_blend`]).
|
||||
fn corners(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str) -> Result<Body> {
|
||||
let counts = record::counts(&[body]);
|
||||
let cur = crate::boolean_record::healed(body)?;
|
||||
let size = cur.size();
|
||||
@@ -1883,27 +1882,10 @@ fn corners(body: &Body, edges: &[Vec3], r: f64, shape: Shape, what: &str, g2: bo
|
||||
if ids.len() != edges.len() {
|
||||
return Err(KernelError::Invalid("no edge near a selected point".into()));
|
||||
}
|
||||
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),
|
||||
})?;
|
||||
let (made, rec) = guard(what, || crate::curveblend::corner_blend(&solid, &ids, size, r, shape == Shape::Round))?;
|
||||
Ok(record::after(record::rebuilt(made, &[&solid], &rec)?, &cur, &counts))
|
||||
}
|
||||
|
||||
/// [`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<Body> {
|
||||
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))
|
||||
}
|
||||
|
||||
/// The step of the radius search: three significant digits of the requested radius.
|
||||
fn radius_step(radius: f64) -> f64 {
|
||||
10f64.powf(radius.log10().floor() - 3.0)
|
||||
@@ -2209,7 +2191,7 @@ fn chamfer_built(body: &Body, edges: &[Vec3], distance: f64) -> Result<Body> {
|
||||
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)))
|
||||
one_by_one().or_else(|e| corners(body, edges, distance, Shape::Flat, "chamfer").map_err(|e2| keep_size(e, e2)))
|
||||
}
|
||||
|
||||
/// `cur` cut by one cutter, with its history over `[cur]` (`None`: nothing left).
|
||||
|
||||
+10
-120
@@ -116,52 +116,9 @@ impl Frame {
|
||||
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<Vec<Vec3>> {
|
||||
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<Vec<Wedge>> {
|
||||
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<Vec<Vec<Vec3>>> {
|
||||
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<Wedge> {
|
||||
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);
|
||||
let (a0, b0) = (self.p0 + self.ta * sa, self.p0 + self.tb * sb);
|
||||
let (a1, b1) = (self.p1 + self.ta * sa, self.p1 + self.tb * sb);
|
||||
// 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()?;
|
||||
@@ -173,18 +130,13 @@ impl Frame {
|
||||
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();
|
||||
let area = 0.5 * (self.ta * sa).cross(self.tb * sb).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<Vec3> {
|
||||
/// `poly` clipped to the half-spaces, each moved `eps` inwards: is anything left?
|
||||
fn reaches_inside(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> bool {
|
||||
let mut cur: Vec<Vec3> = poly.to_vec();
|
||||
for (n, c) in planes {
|
||||
let c = c - eps;
|
||||
@@ -200,53 +152,11 @@ fn clip(poly: &[Vec3], planes: &[(Vec3, f64)], eps: f64) -> Vec<Vec3> {
|
||||
}
|
||||
}
|
||||
if next.is_empty() {
|
||||
return next;
|
||||
return false;
|
||||
}
|
||||
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)))
|
||||
})
|
||||
true
|
||||
}
|
||||
|
||||
/// The body's straight edges between planar faces nearest the points (each once; `None` for a
|
||||
@@ -365,22 +275,11 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
|
||||
// Planar faces are exact in the mesh; curved ones are within the chord.
|
||||
let flat = (sel.size * 1e-7).max(1e-9);
|
||||
let curved = 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)) in sel.frames.iter().zip(&wedges).enumerate() {
|
||||
for (f, w) in sel.frames.iter().zip(&wedges) {
|
||||
let (Some(f), Some(w)) = (f, w) else { continue };
|
||||
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();
|
||||
reaches_inside_beyond(t, &w.planes, eps, &trimmed, out)
|
||||
reaches_inside(t, &w.planes, eps)
|
||||
});
|
||||
if hit {
|
||||
return Some(Clash::Face);
|
||||
@@ -396,7 +295,7 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
|
||||
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) {
|
||||
if meet {
|
||||
return Some(Clash::Blend);
|
||||
}
|
||||
}
|
||||
@@ -404,15 +303,6 @@ fn first_clash(sel: &Selection, size: Size) -> Option<Clash> {
|
||||
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)
|
||||
|
||||
@@ -205,35 +205,19 @@ pub fn fillet_variable_points(body: &Body, edge_at: Vec3, start: Vec3, points: &
|
||||
}
|
||||
|
||||
/// 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`]).
|
||||
/// nearest `start`. One end's radius may be zero.
|
||||
pub fn fillet_variable_spline(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result<Body> {
|
||||
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);
|
||||
};
|
||||
let s = EdgeSetup::new(body, &edge)?;
|
||||
// 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)
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<Body> {
|
||||
// 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> {
|
||||
@@ -586,11 +570,8 @@ pub fn fillet_tapered(body: &Body, edges: &[Vec3], radius: f64) -> Result<(Body,
|
||||
Ok((cur, tapers))
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Chord-length fillet: each edge (straight, between planar faces) rounded so that the blend
|
||||
/// is `chord` wide across; edges with the same face angle share a radius.
|
||||
pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result<Body> {
|
||||
body.require_brep("fillet")?;
|
||||
if !(chord.is_finite() && chord > 1e-6 && chord < 1e6) {
|
||||
@@ -599,44 +580,19 @@ pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result<Body> {
|
||||
if edges.is_empty() || edges.len() > 1000 {
|
||||
return Err(KernelError::Invalid("select 1…1000 edges".into()));
|
||||
}
|
||||
let found: Vec<mt::Edge> = edges
|
||||
.iter()
|
||||
.map(|p| crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}"))))
|
||||
.collect::<Result<_>>()?;
|
||||
// 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<f64> {
|
||||
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.
|
||||
// Radius per edge from its face angle.
|
||||
let mut groups: Vec<(f64, Vec<Vec3>)> = Vec::new();
|
||||
let mut rolled: Vec<Vec<Vec3>> = Vec::new();
|
||||
let mut done: Vec<mt::EdgeID> = 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;
|
||||
for p in edges {
|
||||
let e = crate::surfaces::edge_near(body, *p).ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?;
|
||||
let shell =
|
||||
body.solid.boundaries().iter().find(|sh| sh.edge_iter().any(|x| x.id() == e.id())).ok_or_else(|| KernelError::Failed("edge".into()))?;
|
||||
let faces: Vec<&mt::Face> = shell.face_iter().collect();
|
||||
let fr = edge_frame(&faces, &e)?;
|
||||
let r = chord_radius(chord, fr.phi);
|
||||
match groups.iter_mut().find(|(gr, _)| (gr - r).abs() <= 1e-9 * r) {
|
||||
Some((_, v)) => v.push(*p),
|
||||
None => groups.push((r, vec![*p])),
|
||||
}
|
||||
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]);
|
||||
@@ -644,17 +600,6 @@ pub fn fillet_chord(body: &Body, edges: &[Vec3], chord: f64) -> Result<Body> {
|
||||
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<mt::Edge> = 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)
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user