Compare commits

...
143 Commits
Author SHA1 Message Date
jyvikoandClaude Opus 5.5 507e8e32d2 release: version 0.5.9
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:57:11 -04:00
jyvikoandClaude Opus 5.5 491b3f6212 engine: the heated-bracket guard checks its element count, not wall time
The 60 s limit failed on the Linux CI heavy job (106 s in the test profile) while the
mesh was within its band; the count is what #303's blow-up changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:37:31 -04:00
jyvikoandClaude Opus 5.5 111a6f1a94 Mesh: a face edge split that encroaches a feature edge splits the feature edge
Delaunay refinement split a boundary face edge at its midpoint even when that
midpoint lay inside the diametral sphere of a feature edge beside it. Each such
split halves the face vertices' distance to the curve, so they piled up against
it (the heated bracket grew face vertices 0.016 mm from a 4 mm-sized edge), the
improvement schedule could not lift the tetrahedra there to its target, and
inserted vertex after vertex around them: 29257 elements and about two minutes
to open instead of 23641 and 6 s. The SolidCraft pin move (4c91f9b) added one
interior vertex to the bracket's end faces, which changed the CDT enough to
expose it.

Following Shewchuk (1998), an encroaching midpoint now splits the encroached
feature edge instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 02:17:00 -04:00
jyvikoandClaude Opus 5.5 43e2144090 Docs: the crank's one-datum workflow, its gallery images and the Decompose status
examples.md and mcp.md tell the one-datum workflow and its numbers; the
crank gallery captures and Start card thumbnails are taken again on this
build; ROADMAP marks the automatic blocks of extruded cross-sections done,
and features.md's Decompose entry says what is left (3D parts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:50:49 -04:00
jyvikoandClaude Opus 5.5 8e45f2c275 Samples: the crank meshed from one datum, its half extruded in automatic blocks
crank-arm and crank-mirror now take one datum (Sym) and its partition:
mesh.hex.generate extrudes the half CrankArm/a, cutting its cross-section
into blocks itself, with no seeds, and mesh.mirror reflects it. 8 664
hex20, scaled Jacobian min 0.371; root sigma_xx -62.44/+62.44 MPa against
M/Z 62.6 (0.25 %), spindle reaction 1500 N. The seven partitions and
eleven exact seeds go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:50:49 -04:00
jyvikoandClaude Opus 5.5 86ba1bda5c Release: sign SHA256SUMS.txt with the release key; docs/updates.md (#231)
The release job signs SHA256SUMS.txt into SHA256SUMS.txt.minisig with rsign2 when the
FIELDCRAFT_SIGNING_KEY secret exists, and checks the signature against the public key the app
is built with; without the secret the draft is unsigned, the run warns and the notes say the
app cannot install that release itself. docs/releasing.md says how the key is set up, kept
and rotated; docs/updates.md describes checking, verifying and installing, the web app's
Reload to update, and FIELDCRAFT_UPDATE_HOST for tests. privacy.md, control-protocol.md,
web.md and the roadmap say what changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 93b2ae343c Web: offer Reload to update when a new deployment is out (#231)
Every half hour the page fetches its own address past the browser's cache; when it loads
another content-hashed build of the app than the running one, the status bar offers "Reload
to update" (the page's unsaved-changes question still guards the reload). Rust only, no
service worker: the browser build has no other update path and none of the desktop's
download code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 7dd50a3ca4 App: run update jobs in the background and swap the release in after closing (#231)
The desktop app checks, downloads, verifies and stages on its own threads for the window, and
once the window has closed (autosave closed) swaps a staged release in and starts it. Staging
folders an earlier update left are removed at start-up. Automatic checks stay off under
--control automation and CI unless FIELDCRAFT_UPDATE_HOST names a test server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 2e28a69c04 UI: update notice, Help › Check for Updates and Reinstall, Settings › Updates (#231)
The window checks at start-up at most once a day when automatic checks are on (Settings and
the first run's question), never while that question is open and never without a host, so the
browser and tests make no network call. A newer release shows a quiet notice in the status bar
("FieldCraft X is available — What's new · Install · Skip"); Install downloads and verifies
through the host, then asks to restart, saving or asking about unsaved changes first, and the
host swaps the release in after the window closes. A .deb/.rpm install offers the system's
installer and the command instead. Skip this version is kept in the preferences.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 69c1440cbe CLI: fieldcraft-cli update --check | --install (#231)
--check runs app.update.check and prints its JSON; --install downloads the latest release for
this install, verifies the checksum list's signature and the asset's checksum, and swaps it in
(or, for .deb/.rpm, prints the package manager command for the verified download). Tested
against a local release server through FIELDCRAFT_UPDATE_HOST.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 12487794a3 Engine: app.update.check reports whether a newer release is published (#231)
The same check as the app's Help › Check for Updates and fieldcraft-cli update --check: the
latest release, whether it is newer, its page, whether it is signed and the asset this install
would download. It only reports. Checking reaches the network, so only the desktop app and the
CLI switch it on; tests, scratch sessions and the browser build refuse without asking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 8fe31545ea Update: check, verify and stage releases in a new fieldcraft-update crate (#231)
Versions ordered as SemVer, the GitHub Releases API reply read as hostile input, how this
copy is installed (macOS app or CLI, Windows folder, AppImage, tar.gz folder, .deb/.rpm) and
which release asset updates it, the checksum list's minisign signature checked against the
built-in release key, the asset's SHA-256 checked against the list, archives unpacked inside
the staging folder, and the swap planned and applied by renames with undo on failure. The
network and unpacking parts are native only; a mock release server drives the tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:48:30 -04:00
jyvikoandClaude Opus 5.5 4c18322a34 Engine: the half crank extrudes in blocks through mesh.hex.generate and mesh.cells
The extrusion's automatic cross-section blocks reach both commands; the
half crank arm, cut only on its symmetry plane, meshes all-structured
(sJ >= 0.37) with no seeds either way, and mesh.hex.generate's
description says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:26:30 -04:00
jyvikoandClaude Opus 5.5 02172f9a7e Mesh: swept cross-sections cut into blocks automatically
A region of an extrusion's (or revolution's) cross-section that no
structured scheme fits is now cut by straight lines into blocks that fit,
before interval assignment, so the cuts are curves of the arrangement and
their counts are assigned with the rest; nothing reaches the model
(hex::decompose, after Tam and Armstrong's medial-axis subdivision and Li,
Armstrong and McKeag's primitives).

Per region: several holes are separated by lines across the gaps between
neighbouring holes; a piece with one hole gets the O-grid layout whose
pieces score best (lines from the outer corners towards the hole or along
their bisectors, from the hole's corners, or along four directions from
the hole); pieces without holes are cut by a two-ply search over lines
from concave corners and fillets and from convex corners. Candidates are
scored by meshing the pieces with their schemes (smallest corner scaled
Jacobian). A region's blocks are kept when fair (at least 0.5) or no worse
than its free mesh, and cuts never end inside a seeded curve.

This replaces the cuts from reflex corners along an edge. Tests on an L,
a T, a plate with a hole, with a slot and with three holes, and the half
crank's cross-section: every region structured, the quads conforming and
the smallest corner scaled Jacobian bounded. The half crank arm now
extrudes in 12 structured regions with a hex20 minimum scaled Jacobian of
0.37 (the arm meeting the bosses 20 degrees off tangent bounds it) where
it had 2 free regions and 0.009.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:17:30 -04:00
jyvikoandClaude Opus 5.5 a0b4a69452 Mesh: the swept cross-section's quad mesh as its own module
The schemes, interval constraints, curve nodes and region meshes of a
multi-level sweep's cross-section move out of layered::mesh into
hex::section, with the curve placement (seeds, projection onto walls)
passed in, so the cross-section can be meshed on its own.
region::mesh_structured gives a scheme's mesh or None where it would fold,
without falling back to the free mesher. No change in behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:17:30 -04:00
jyvikoandClaude Opus 5.5 c83b803f63 web: the deployed browser build carries the PostHog key (#305)
Pages builds main with the repository secret POSTHOG_KEY, so web users are asked
the same consent question as desktop users; develop builds stay keyless.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:13:55 -04:00
jyvikoandClaude Opus 5.5 db80b75814 Docs: privacy.md lists every usage event; release builds get the key (#238)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 31bc886c7a Web: usage through fetch, preferences in local storage (#238)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 ed9ec7748d App: send usage batches to PostHog Cloud EU from a background thread (#238)
ureq over rustls (ring) with the OS certificate verifier. The project key
is the build-time FIELDCRAFT_POSTHOG_KEY; without it nothing is asked or
sent. FIELDCRAFT_TELEMETRY=0 turns it off; --control and CI runs only with
FIELDCRAFT_TELEMETRY=1. A failed post drops its batch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 79d583ea0f UI: ask once about anonymous usage; Help › Settings › Privacy (#238)
The first run asks whether to share anonymous usage (only when the host
says this run may), the answer and a random install id are kept in the
preferences, and Help › Settings… changes it. Commands are counted by
where they came from (ui, palette, script; mcp when the MCP server says
so), and cancelled forms and clicks on commands that cannot run yet are
recorded. The preferences go through a PrefsStore (a file, or the
browser's storage). Control channel: ui.settings, ui.prompt answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 162bb421f1 Engine: anonymous usage events, counted in Session::execute (#238)
fieldcraft_engine::usage holds the events docs/privacy.md lists, typed so
that only registry names (command ids, sample names, requirements) and
durations can go in them, a bounded queue that records nothing until the
host enables it, and the PostHog batch body. Session::execute counts each
top-level command of a session with an origin (ui, palette, script, mcp):
its id, kind, duration and error class, and the funnel's milestones and
opened samples. Nothing here touches the network.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:07:28 -04:00
jyvikoandClaude Opus 5.5 54f50f9518 Gallery: every example image captured again on the current build
All six docs/media/examples images at 1400 x 860 in the light theme, the
solved sample in the home view (the crank mirror from below, as its text
says), with the wireframe symbols, no SETUP card and the crank's planes
hidden; the Start card thumbnails cropped to the model from them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 a0d11f1c22 Partitions hide their datum plane
geometry.partition hides the plane it cuts by (view state, saved with the
model): the cut shows as edges on the cells. The eye or selecting it in
the browser shows it again. The crank samples so open without their
planes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 dddb2d0584 Datums: drawn at the model's extent, never framed, the selected one shown
A datum plane is drawn as the model's extent within it (where it cuts the
model's box, in the plane's axes) plus a 5 % margin, a datum axis along the
model's extent plus the margin, instead of squares 1.2 diagonals wide.
Fit, Home, the standard views and headless pictures frame the model
without the datums (they stay inside the clipping radius). The datum
selected in the browser is drawn highlighted and on top, even when hidden.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 01:01:43 -04:00
jyvikoandClaude Opus 5.5 b19277ae7a Docs: crash reports, the log file, Report a Bug and privacy (#107)
docs/crash-reports.md: what is kept where, what a bug report carries
(and only when ticked), the CLI and commands for agents; README's
privacy note; the control protocol's new prompt answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 e06c85eb9e App: crash reports and a log file; Help › Report a Bug (#107)
The desktop app installs the crash reporter and a log file at start
(both in a temporary folder in --control and CI runs, #266), journals
the window's commands (background jobs included) and every control
request's method, and ends the journal on a clean exit. A start after a
crash asks: "FieldCraft closed unexpectedly", Report It… or Not Now.

Help › Report a Bug (also Tools › Help and ui.start
diagnostics.bug_report) shows exactly what the GitHub bug form will be
filled with: the version, the OS, the last error, and for a crash where
it happened. Share my session adds the replayable commands, Include the
model file the model. Open GitHub Issue opens the form in the browser
through the system's opener; files to attach are saved to
bug-reports/<time>/ and a long session goes on the clipboard. Nothing is
sent without that click and the user's submit on GitHub.

The control channel answers the new prompts (crashed: report, close;
report_bug: set, close) and ui.inspect shows the draft; it never opens
the browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 cb7e3a2711 CLI: fieldcraft-cli crashes [list|show|replay|dir|clear] (#107)
Lists, shows, replays and deletes the crash reports the desktop app
wrote. A replay opens the report's model, runs its commands with writes
confined to a scratch folder, and says whether the same internal error
happens again. Adapted from SolidCraft's solidcraft-cli crashes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 080ff048c6 Engine: crash reports, a log file and bug report drafts (#107)
crash: a panic hook and a locked per-run command journal (adapted from
SolidCraft's crash reports). A panic in a command becomes a report with
the model from before it and the command; one outside commands, or an
unclean exit found at the next start (abort, segfault, a crash in a
graphics driver, a kill: what #248 needs), a report with the model the
journal starts from (autosave, file or a copy) and the commands since,
the last control request and the dead run's log lines. Reports are
bounded, deduplicated by signature and replayable (crash::replay, with
writes confined to a scratch folder). The crash folder follows the
automation temp area in --control and CI runs.

logfile: a small size-rotated file logger behind the log facade.

bug_report: GitHub bug-form drafts. Version, OS and what happened by
default, home folder shown as ~; the command journal only with Share my
session, the model only with Include the model as well; a session too
long for the link becomes a file to attach and the clipboard text.

Commands: diagnostics.crash_reports, diagnostics.crash_report,
diagnostics.bug_report (Tools › Help, with its icon) and
diagnostics.crash_test (FIELDCRAFT_CRASH_TEST=1 only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 3d51bde9dd io: the app's data folder, and confining writes alone
recovery::data_dir() names the per-user data folder (the temporary
fieldcraft-automation folder in automated runs) that the recovery, crash
and log folders live in. Roots::writes_within lets reads go anywhere
while writes stay in one folder, for replaying a crash report safely.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:36:18 -04:00
jyvikoandClaude Opus 5.5 d3ed8ffb05 Start card: every sample as a card with its thumbnail, flagship first, scrolling (#245)
The Start card and File › Samples show a grid of sample cards (thumbnail, name,
one-line description, the full text on hover) in a scroll area with a solid
scrollbar; Help › Samples keeps rows in the same order. The card stays clear of
the view cube and the navigation bar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:06:20 -04:00
jyvikoandClaude Opus 5.5 072139353f Samples: 320 px thumbnails cropped from the gallery captures
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-15 00:06:20 -04:00
jyvikoandClaude Opus 5.5 08f669acad Browser and viewport: item menu, per-item eyes, Delete key with confirmation
Right-click on any browser item (body, surface, datum, partition, set,
material, section, step, boundary condition, load, reference point,
coupling, contact, fluid domain) opens its menu: Edit…, Hide/Show,
Isolate, Show All, Active in step (boundary conditions and loads) and
Delete…. A right click on a datum or a partition's cut face in the
viewport opens the same menu. Each item the viewport draws on its own
has an eye; hidden items are neither drawn nor picked. Datums and
partitions are selectable with properties. Delete… and the Delete key
ask first (the prompt lists what uses the item: a datum's partitions
are deleted with it, other definitions in use are refused); ui.prompt
answers it. Every entry runs the same command as the ribbon and forms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 d7ec7f486a View state: hide, show and isolate viewport items, saved with the model
view.hide, view.show, view.isolate and view.show_all change which
bodies, surfaces, datums, boundary conditions, loads, reference points
and couplings the viewport draws. The hidden items are view state: the
manifest's `view` keeps them, a change marks the model unsaved, but it
is neither journalled nor undone and leaves results current. Items that
go away are forgotten. Headless pictures leave hidden items out; the
glyph builders take a filter. Tools > View > Show All claims the
commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 d9824de4a5 Engine: geometry.datum.point; planes and axes through datum points; datum edits and cascading delete
A datum point by coordinates, at a mesh vertex, a fraction along a
design edge, at a face's centre, or where a datum axis crosses a datum
plane. Datum planes take three datum points or a normal to a datum axis;
axes take two datum points. geometry.datum.edit, .axis.edit and
.point.edit redefine a datum of their kind (partitions cut again);
geometry.datum.delete with cascade also deletes the partitions that cut
by it. The ribbon shows Datum Plane, Datum Axis, Datum Point and
Partition, each with its own icon; edit and delete leave the ribbon
(still commands, claimed by their entries).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 fbaba5fecd Geometry: a face's area centroid and a point a fraction along an edge
Shape::face_centre and Edge::point_at place datum points on a design's
named faces and edges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 0bf150633c Model: datum points, drawn as a small cross; each definition's users are public
Datum::Point joins planes and axes (checked like them, refused by
partitions with the kind named). The users each remove_* refuses with
(sets, materials, boundary conditions, loads, reference points, fluid
domains, datums) are public functions, so a caller can list them before
deleting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:51:01 -04:00
jyvikoandClaude Opus 5.5 c1fd58c6ce release: version 0.5.8
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:33:11 -04:00
jyvikoandClaude Opus 5.5 90948833e0 Samples: the crank arm meshed structured from a partitioned half
crank-arm (and crank-mirror, kept as the same model under the name of
its mirror workflow) now cut the crank on its symmetry plane and the
half into seven cells: across the arm at x = 30, 60, 110 and 148, and on
two diagonals radial to the pocket's corner fillets. Every cell's
cross-section maps (four-sided blocks, the half O-grids round the bores,
triangle primitives at the pocket's corners); exact edge seeds give each
cut the same divisions on both sides, so mesh.cells merges all six cuts
and mesh.mirror reflects the half: 7 710 hex20, scaled Jacobian min 0.37
(was 0.17, and 0.009 for the swept mirrored half), edge ratio at most
7.0. Root σxx ±62.43 MPa against M/Z 62.6 MPa, the spindle carries the
1500 N. The test asserts the quality floor. Gallery images regenerated.

Fixes #247

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:17:20 -04:00
jyvikoandClaude Opus 5.5 73987bdbae Mesh: the triangle primitive for three-cornered sweep regions
A cross-section region with three corners (a fillet's quarter disk, a
pocket corner cut off by a partition) was left to the free all-quad
mesher. It now gets midpoint subdivision's triangle primitive (Tam and
Armstrong 1991; Li, Armstrong, McKeag 1997): lines from a centre to a
node on each side split it into three mapped blocks, the interior then
smoothed and every quadrilateral checked (a fold falls back to free).
Interval assignment gains dominance constraints (a side shorter than
the other two together) so the split always exists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:17:20 -04:00
jyvikoandClaude Opus 5.5 7df37d4b15 README: the setup symbols screenshot redrawn with the wireframe symbols
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:14:40 -04:00
jyvikoandClaude Opus 5.5 52c12e2ad7 Setup symbols: wireframe glyphs per held degree of freedom, a constant size on screen
Boundary condition, load and interaction symbols are wireframes (thin lines,
no shaded cones), so they never hide the mesh or a contour plot:

- a crossed wire triangle per constrained translation, tip on the node,
  coming from outside the part where the set's faces say which side that is;
  a held rotation adds a smaller triangle behind it (the double mark); fixed
  shows all three axes, a symmetry plane only its normal;
- forces as open-headed arrows ending on the node, as long as four support
  units at one place and 2.5 over a set, so loads and supports stay in
  proportion (#78); moments as an axis line and a right-handed curved arrow
  (#79); contact and tie surfaces as small squares on their faces;
- a constant size on screen at any zoom (#80): the symbol unit is the size
  setting (View > Symbol size, `ui.set {symbol_size}`, 14 pt by default)
  times the model length a pixel spans, rounded to a quarter of a doubling;
- spread evenly on a grid a few symbol units across, so their density follows
  the screen, never more than 400 per definition;
- a layer of their own on the desktop (GPU and CPU): zooming rebuilds and
  uploads the symbols only, never the mesh's scene; framing leaves them out;
- colour per kind from the theme's tokens (a new contact colour), and the
  definition selected in the browser drawn in the selection colour, wider;
- depth-tested against the model with the line bias that keeps them on their
  own surface; a load at a reference point or a single node and a reference
  point's cross are drawn over the part (#78).

Headless pictures (MCP screenshot, `ui.render`) frame the camera first and
draw the symbols at the default size for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:14:40 -04:00
jyvikoandClaude Opus 5.5 1fcc7acf84 render: lines drawn on top, any number of overlay layers, length per pixel
A scene's `on_top` lines are drawn after every depth-tested layer, over the
model, so a concentrated load at a point inside the part can be seen from any
side (#78). `render_layers` takes a list of overlays (the setup's symbols and
the selection highlight become separate layers), and draws every layer's
labels. `Camera::length_per_pixel` is the model length a pixel spans at the
target: the scale symbols of a fixed screen size are drawn at.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:14:40 -04:00
jyvikoandClaude Opus 5.5 3aab588b8b Navigation: orbit about the point under the cursor, zoom toward it, presets in the display menu
An orbit turns about the model point under the press (the pick ray's
first hit on the plot, the mesh or the design), or the centre of what is
drawn when it starts on empty space, keeps that point still on screen and
marks it while orbiting. The wheel and a pinch zoom toward the point
under the cursor; the wheel's delta is read as it arrives, so a notch
zooms in full in orthographic and perspective views alike (#273).

Mouse presets and reverse zoom come from SolidCraft (prefs.rs NavPreset,
NAV_PRESETS; MIT OR Apache-2.0): FieldCraft's own (left drag per the
navigation bar) stays the default, Ctrl + left drag from empty space
orbits in every preset. They are chosen in the display menu, settable
with ui.set and kept in prefs.json beside recent.json (the browser build
keeps them for the page's run); an older prefs.json still loads.

Fixes #262, fixes #273.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:02:34 -04:00
jyvikoandClaude Opus 5.5 f074e10442 Render: Camera::orbit_about turns the view about a pivot that keeps its place on screen
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 23:02:34 -04:00
jyvikoandClaude Opus 5.5 05abcec6c2 engine: the crank-arm conformity test checks all-hex20, not a platform-dependent count
The tet-free sweep gives 7274 hex20 on macOS and 7334 on Linux (#115), so the exact
count failed develop's CI after #272.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:49:31 -04:00
jyvikoandClaude Opus 5.5 012119e2c2 Remove the SETUP card: the browser tree shows the progress
The setup checklist card (#265), its show_setup view setting, the View
menu checkbox and the preferences file that only remembered it go; the
tree's marks and ghost rows replace them. Session::progress and
model.check's progress stay for agents. An old prefs.json is no longer
read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:49:07 -04:00
jyvikoandClaude Opus 5.5 f5a84f5f74 Browser: setup state marks and ghost rows on the tree
Each top-level node that is a setup stage carries a mark at the right
of its row beside its count (done, next, blocked) with the reason and
place in its hover, and a node still lacking what its stage needs shows
a ghost row that starts the providing command. ui.inspect reports each
node's state as browser.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:49:07 -04:00
jyvikoandClaude Opus 5.5 910d437819 App: ask before a mesher replaces a body's mesh
The form's OK on a mesher whose body already has a mesh opens a Replace
mesh prompt ("CrankArm already has a mesh (7,274 hex20). Replace it?"),
naming sets that list the old labels and results that will be cleared.
Replace runs the form; Cancel leaves it open. The control channel's
ui.dialog submit is the OK button, ui.prompt answers replace or cancel.
Programmatic calls never ask. Fixes #267.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:45:24 -04:00
jyvikoandClaude Opus 5.5 0e4ea5e099 Meshers replace the mesh of the bodies they mesh, and only theirs
mesh.tet.generate and mesh.planar stacked a second mesh on a meshed body;
mesh.hex.*, mesh.hex.octree and mesh.cells wiped every body's mesh. All of
them, and mesh.mirror for its image bodies, now go through replace::clear:
the body's old elements and the nodes only they use go, other bodies stay.
The reply reports replaced {body, elements, nodes}, stale_sets (sets that
listed the old labels) and results_cleared; the command is one undo step.
replace::MESHERS names the bodies each mesher fills, and replacement()
says what a run would replace, for the app to ask first. mesh.block stays
additive: a body is built from several blocks. Refs #267.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:45:24 -04:00
jyvikoandClaude Opus 5.5 ed2541170a Model: remove one body's mesh, and list the sets that named its labels
Model::remove_body_mesh drops the elements that fill a body and the nodes no
other element uses, with their tags; Model::sets_using names the sets that
listed any of them by label. The base of per-body remeshing (#267).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:45:24 -04:00
jyvikoandClaude Opus 5.5 0bbdd463ea Cells: the blocks refusal names its problem as a schema Problem
develop did not build: #277's new refusal in mesh.cells passed text to
EngineError::param, which #276 changed to take a ProblemKind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:45:24 -04:00
jyvikoandClaude Opus 5.5 65fb1112ab Engine: EngineError::Param carries the schema Problem at its field's path
The ~40 parameter checks give a ProblemKind instead of text; Session::execute looks the problem
up in the command's form (a group's missing field becomes that field's own path). Replies still
name keys; forms phrase the same problem by label. A test refuses every field of every form and
checks each refusal names a field of that form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:42:19 -04:00
jyvikoandClaude Opus 5.5 de8b7b6321 Schema: one phrasing of a problem, by key or by label; Required by field kind
Problem::phrase serves both for_agents and for_form. A required name says "enter a name", a
path "enter a path", anything else "required" (no more "Autosave: enter an autosave"). New
kinds for what commands check (positive, range, list, name, path, invalid), and refine() to
look a command's problem up in its form.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:42:19 -04:00
jyvikoandClaude Opus 5.5 70c5c9b26f Ribbon: Hex Mesh and Partitioned Mesh replace the duplicate hex entries (#270)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:35:17 -04:00
jyvikoandClaude Opus 5.5 f4b6d1dbff mesh.cells: "default": "blocks" runs mesh.hex.blocks; labels Hex Mesh, Partitioned Mesh
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:35:17 -04:00
jyvikoandClaude Opus 5.5 2d5dfb2137 Forms: a one-line note per choice; the hex Method says what each needs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:35:17 -04:00
jyvikoandClaude Opus 5.5 ad84a52ed2 Viewport: one framing rule for open, results, fit, home and standard views
Every fit frames what is drawn (the deformed shape and the setup's symbols
included) with Camera::fit_in in the part of the viewport the overlays
leave free: the results legend, the selection bar, the gizmo and the
navigation bar (framing::free_part). Standard views fit too, so a long
beam's front view keeps both ends (#147); fit and home leave the legend
clear (#76). The view frames itself in the home view when another model,
sample or design is opened (Session::opened; the same design opened again
after an edit keeps the camera) (#233), and when results come up with part
of the model out of sight (#223). ui.inspect's layout reports the legend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:29:44 -04:00
jyvikoandClaude Opus 5.5 5758dc7911 Results: a static step first shows its contours undeformed
The first look at a solved static step draws the von Mises contours on the
true geometry; the deformed shape comes when asked for (Deformed,
results.deformed, results.animate), at the automatic scale. Frequency steps
still open on mode 1 deformed and explicit steps at true scale, as the
owner's notes in #77 ask; a 0.24 mm deflection drawn as 10 mm no longer
reads as a failed part.

Fixes #77

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:29:44 -04:00
jyvikoandClaude Opus 5.5 29af2aef91 Camera::fit_in frames a box's corners in part of the view
The distance and the target follow from the eight corners' exact
projections, for orthographic and perspective cameras and any direction of
view, so a long beam seen side on fills the width instead of a sphere
around it the height (#147). The free part is given as fractions of the
view, so overlays can be left out (#76); a margin is kept on each side.
Camera::fit is fit_in over the whole of a square view, and the headless
renderer fits to the picture's aspect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:29:44 -04:00
jyvikoandClaude Opus 5.5 696b64c30f Session::opened identifies the open document
It changes when file.open, file.recover or file.sample replaces the session
and when geometry.open opens another design file or starts a new model; an
edit, a solve or reopening the same design keep it. The desktop app frames
the view on that change (#233).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:29:44 -04:00
jyvikoandClaude Opus 5.5 a0f48c7207 render: quadratic elements draw through their mid-side nodes; geometry edges over the mesh follow it
Zoomed in on the hex20 crank arm, the element edges and the shaded faces
did not meet (#260). The mesh is conforming; the display drew each hex20
face and edge as straight chords between corners while the mid-side
nodes lie on the curved surface (up to 0.44 mm off the chord at 3 mm),
and drew the geometry's face boundaries from the design tessellation,
off both.

Now a quadratic face is cut into triangles whose vertices are its
corners and mid-side nodes, each edge is drawn as its two halves, and
over the mesh the geometry's edges (and a hovered design edge) are drawn
as the element edges on geometry edges (`DisplayEdge::feature`), so
faces, edges, feature lines and the highlight share their vertices.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:13:15 -04:00
jyvikoandClaude Opus 5.5 9e38fe866d mesh: conformity check finds cracks (free faces, open edges, duplicate nodes, mid-side mismatches)
`quality::conformity` checks a solid mesh for cracks: the free faces must
close up (every corner edge on exactly two), no two distinct nodes may
coincide, and every element edge has one mid-side node. The hex tests
assert it for every method, hex20 included, and the crank arm sample's
7274 hex20 is conforming (#260: the disjoint lines are a display issue).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:13:15 -04:00
jyvikoandClaude Opus 5.5 c26b142630 Recover: each entry's age, and Discard all
file.recovery.list gives each entry's age; File › Recover shows name, age and counts, newest
first, with Discard all. docs/formats/fieldcraft.md states the folder and pruning rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:11:13 -04:00
jyvikoandClaude Opus 5.5 6bb3b04e60 App: a --control run keeps its autosaves out of the user's recovery folder
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:11:13 -04:00
jyvikoandClaude Opus 5.5 b1180bf987 IO: automated runs autosave into a temporary folder; stale entries prune themselves
Runs driven by automation (use_automation_dir) and CI use fieldcraft-automation/recovery in the
temporary folder unless FIELDCRAFT_RECOVERY_DIR is set. Taking a slot deletes left-behind
entries older than 14 days and those whose model was saved since.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 22:11:13 -04:00
jyvikoandClaude Opus 5.5 786121c21a UI: a setup checklist at the top of the browser
Once a model has geometry or a mesh, the browser shows the analysis stages from the engine's
checklist, each ticked, next, dashed (optional) or open; a click starts the stage's command and a
blocked stage's hover says what it waits for. The × hides it and View › Setup checklist shows it
again; the choice is kept in the per-user prefs.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:46:33 -04:00
jyvikoandClaude Opus 5.5 e223a6256a MCP: check_model describes the setup checklist it returns
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:46:33 -04:00
jyvikoandClaude Opus 5.5 fe557054ef Engine: the setup checklist (Session::progress), returned by model.check
The analysis stages in order (geometry, seeds & partitions, mesh, material, section, sets,
boundary conditions, loads, step, solve, results), each done, next, todo, blocked or optional,
with the command that does it. Built on the command requirements; Solve also reads the model
check's first error.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:46:33 -04:00
jyvikoandClaude Opus 5.5 fc85550534 UI: a form's label column fits its longest label, long labels wrap, fields fill the row
The column is measured from the form's labels, at most 45 % of the form's
width; a longer label wraps onto two lines (the column widens only when
two are not enough) and its required and help marks follow it inside the
column. Fixes labels cut at a fixed 112 pt ("Hardening modu…").

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:45:06 -04:00
jyvikoandClaude Opus 5.5 3d8864c313 UI: browser rows keep their count and bias visible, long names elide in the middle
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:45:06 -04:00
jyvikoandClaude Opus 5.5 2443746b35 UI: status messages elide in the middle, the command line's placeholder fits its width
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:45:06 -04:00
jyvikoandClaude Opus 5.5 8b12cdd5c7 UI: field help on hover and an (i) mark, units without a unit system, X/Y/Z captions
A form row's label and its drawn (i) mark show the field's help and unit
on hover. With no unit system a number shows its dimension ("[stress]")
and the form says where to set the system (Properties › Units). Vector
components are captioned (X, Y, Z, or the field's own names such as E1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:29:07 -04:00
jyvikoandClaude Opus 5.5 6b9e669c7e Engine: every form field says what it means, and shows its unit or dimension
Field gains `help`: one or two sentences of our own wording with a
typical value (yield stress: the initial yield, 276 MPa for 6061-T6,
250 MPa for mild steel; hardening modulus explained; and so on), set
next to each field in cmd/forms.rs. Dim::name gives the dimension
("stress"), Field::unit_label the unit or, with no unit system, the
dimension in brackets, and Field::help_text the tooltip with the unit or
where to set the unit system. The JSON Schema description carries the
help too. A test checks every form field has help and every dimensioned
field shows a unit or dimension in every system.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:29:07 -04:00
jyvikoandClaude Opus 5.5 eb66b86e26 Engine: the meshing commands pass the design's edge seeds to the meshers
mesh.tet.generate, mesh.hex.*, mesh.hex.blocks and mesh.cells give every
seed on the open design to their meshers, which match them to their own
curves by position, so a seed on an edge two cells share holds in both. The
tet reply gives, per seed, the mesh edges along it. Docs and the roadmap
say what is honoured where.

Fixes #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:23:05 -04:00
jyvikoandClaude Opus 5.5 f78680e091 Mesh: the tet mesher divides a seeded edge at the seed's nodes
The seed's spacing becomes size-field samples the field grades from, and
after coarsening its nodes are put on the feature curve and pinned, so the
edge has exactly the seeded divisions at the seeded spacing. The quality
report gives, per seed, the boundary edges along it.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:23:05 -04:00
jyvikoandClaude Opus 5.5 13b506150c Mesh: the hex meshers honour edge seeds
A seed is matched to a mesher's curve by position (ends and middle within the
two tessellations' tolerance), which also orients its bias. Interval
assignment holds exact seeds, raises minimums and takes free seeds as goals;
an equality, loop minimum or parity it cannot meet with the exact seeds held
names them. Seeded curves get the seed's spacing. Extrude and revolve seed
cross-section curves and the layers of a level interval; sweep and mapped
seed their B-rep edges; cells seed the shared edge once, so both cells keep
it and stay conforming.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:23:05 -04:00
jyvikoandClaude Opus 5.5 bdd84a491d Schema: a problem carries its field and a structured kind, phrased by label or by key
schema::Problem now holds the &'static Field it is about and a ProblemKind
(Required, NotANumber, Below, Above, NotAChoice, UnknownVariant, ...).
Problem::for_form phrases it by the field's label, Problem::for_agents by
its JSON path, from the same data. The form no longer rewrites problem
text by string matching or re-walks the field tree; field_at moves to
schema.rs for the engine's own Param errors. The forms test matches
EngineError::Param { key, .. } directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 21:09:22 -04:00
jyvikoandClaude Opus 5.5 904dc3381b UI: form problems name fields by their labels, and OK waits for required fields
Every problem reads with the field's label ("Material: choose a material")
beside its field, once it was edited or OK was tried; a click on the greyed
OK shows them all, and its tooltip lists them. A parameter the command
refuses shows beside its field, by its label, in the form and status bar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:58:45 -04:00
jyvikoandClaude Opus 5.5 9dcbb9c9a6 Engine: a parameter error carries its key and problem (EngineError::Param)
A form can show the problem beside the field it is about. The message
still names the key, as before, for agents.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:58:45 -04:00
jyvikoandClaude Opus 5.5 8df4ea040c UI: seeds as ticks along their edges, Mesh › Seeds, and seeding the selection
A seed draws a tick at each node it puts on its edge, so a bias shows as ticks
crowding toward an end. The browser lists the seeds under Mesh; a click
selects the seeded edge. The Seed Edges form takes the selected edges with
Use selection. The toolbar entry is ready (its icon renamed with it).

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:58:17 -04:00
jyvikoandClaude Opus 5.5 e8cada94d0 Engine: mesh.seed.edge, mesh.seed.clear and mesh.seed.list
Seed design edges by their persistent names with a count or a size, a bias
and a constraint; one undo step each, saved with the model. Seeds on edges a
reopened design lacks are reported as stale.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:58:17 -04:00
jyvikoandClaude Opus 5.5 f8e0be970e Model: edge seeds — a count or size per edge, bias and constraint
A seed names a design edge and asks for a number of divisions or a target
length, optionally graded geometrically toward the start, the end or both
ends, kept exactly, as a minimum or as a free goal. Seeds are saved with the
model; Seed::spacing gives the node positions meshers and the viewport share.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:58:17 -04:00
jyvikoandClaude Opus 5.5 94c98e0c0b UI: pick a design's edges by their persistent names
The viewport keeps each drawn body's B-rep edges; with Select: Edges a click
picks the nearest visible one (before and after meshing), hover and the
selection draw it wide, and multi-select works as for faces.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:46:05 -04:00
jyvikoandClaude Opus 5.5 ffb71de6e1 Engine: geometry.bodies lists each body's named edges
Each edge with its persistent name and length. A reference to an edge name
selects its numbered pieces (`~k`), as a face name selects its `#k` pieces.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:46:05 -04:00
jyvikoandClaude Opus 5.5 a11b971dae Geometry: persistent edge names, after the faces each edge separates
A design edge is named by its faces' persistent names, sorted and joined by
`|`, numbered `~k` by position when several separate the same faces. The
names follow the faces through a design edit and a partition replay.

Part of #230.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:46:05 -04:00
jyvikoandClaude Opus 5.5 6bfa0b410a UI: a reference field is always a drop-down; with nothing to pick it offers Create …, and one candidate starts picked (#215)
A reference field (a material, set, step…) with no items was a free-text box; it is now a greyed
drop-down ("No materials yet") with a button that opens the command making one (the
collection's requirement provider). That form comes back to this one on OK, with the new item
picked, or as it was on Cancel. A required reference with one candidate, or with the browser's
selection of its kind, starts picked when the form opens, so the fields and the JSON view agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:34:24 -04:00
jyvikoandClaude Opus 5.5 29e7a4ca31 Engine: a reference collection names the requirement (and its provider) that makes an item
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:34:24 -04:00
jyvikoandClaude Opus 5.5 794122a302 MCP: the partition, cell and mirror commands in the instructions and docs
The mesh tool runs mesh.cells (method cells) and mesh.mirror (method mirror).
The server instructions and docs/mcp.md list the partition, per-cell, mirror
and symmetry commands and point to the crank-mirror sample.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:23:04 -04:00
jyvikoandClaude Opus 5.5 860707efa6 Sample: crank-mirror, the crank arm meshed from a half and mirrored
file.sample crank-mirror partitions the crank arm on its symmetry plane, sweeps
one half all-hex (hex20) and mirrors it into one conforming mesh, then defines
the crank-arm model. Samples may now run preparing commands (datums,
partitions) before their script sees the bodies. Its test checks the halves
alike and joined, every element valid and the sets on both halves; the heavy
test solves it: sigma_xx at the root -62.43 / +62.43 MPa against M/Z = 62.5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:23:04 -04:00
jyvikoandClaude Opus 5.5 a84a8339ae UI: command replies read as one line, the whole reply in the context panel
Commands run from the UI whose reply had no `summary` printed their raw
JSON into the status bar (Check Model, Step Table, Model Info, Bodies,
Find Contacts, the solve steps...). The status bar now gets one sentence
for every reply, and a reply with more to it opens in the context panel:
Check Model as its diagnostics with severity marks and a button to each
fix, the Step Table as a grid of loads and BCs against steps, any other
reply as labelled rows and tables. Check Model and the Step Table follow
the model as it changes. Programmatic replies stay JSON.

Fixes #217

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:18:04 -04:00
jyvikoandClaude Opus 5.5 f89545a66a Engine: model.boundary_condition.symmetry on a datum plane
A symmetry condition (zero normal displacement, zero rotation about the
in-plane axes) on a datum plane normal to X, Y or Z, with its set given or made
of the open design's faces on the plane (a partition's cut faces), so half a
symmetric part is solved as a half. Half a 40 mm bar cut at its mid-width, with
the condition and half the load, bends as the whole bar to 2e-12 with half the
reaction. Inclined planes are refused as not supported yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:08:42 -04:00
jyvikoandClaude Opus 5.5 0f99a1c687 Engine: mesh.mirror reflects meshed bodies across a plane
The bodies' elements are reflected across a datum plane (or a point and
normal) with fieldcraft_mesh::mirror and joined on it. The image is tagged as
the design's body at the reflected place (found by volume and centroid, or
named in `as`), its faces with that body's faces under them, so sets by face
name reach both halves. Half a bar meshed hex8 or hex20 and mirrored has the
whole bar's node and element counts and volume, and its bending deflection to
1e-12; tet4 and tet10 mirror valid and conforming.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:00:59 -04:00
jyvikoandClaude Opus 5.5 9fc8e27933 Geometry: the nearest face of a body to points
Shape::nearest_faces finds, for each point, the face whose tessellation lies
nearest: how a mirrored mesh finds the faces of the body it is the image of.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:00:59 -04:00
jyvikoandClaude Opus 5.5 b73a3bb976 Mesh: mirror elements across a plane, right-handed, sharing the plane's nodes
fieldcraft_mesh::mirror reflects a region's tet4, tet10, wedge6, hex8 and hex20
elements across a plane. The copies list their nodes in reflected order (corners
swapped, mid-side nodes following their edges), so every copy is right-handed;
reflected_faces and reflected_edges give the copy's face and edge over the same
nodes. Copies of the nodes on the plane are merged with the originals through
join::merge_coincident, so the region and its image form one conforming mesh.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 20:00:59 -04:00
jyvikoandClaude Opus 5.5 7d689fb6a2 UI: the CPU viewport image never exceeds the texture size limit
A Retina window 2300 pixels wide drew its CPU viewport (the offscreen capture's
path) into a 2300 x 1412 texture, past egui's 2048 limit, and the app aborted.
The image is now scaled to fit the context's max_texture_side and drawn
stretched, as an image over the renderer's own limit already was. Fixes #237.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:50:37 -04:00
jyvikoandClaude Opus 5.5 0b6b6c966c Engine: mesh.cells meshes a partitioned part cell by cell
Each cell (a body of the open design) gets its own method: structured hex where
one fits (auto falls back to tet and says why), or tet. All go into one mesh.
Cells on either side of a partition are joined: where their element faces
match node for node the nodes are merged; otherwise (hex next to tet, or
different divisions) the two partition faces get a set each and a dual mortar
tie, the reported hex-tet transition. A 40 mm bar cut in half, one half hex,
the other tet, stretches F L / (E A) to 1e-6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:50:37 -04:00
jyvikoandClaude Opus 5.5 1fbb5581ea Mesh: merge coincident nodes, keeping tags and sets on the survivor
Model::merge_nodes replaces merged nodes by their survivors in elements (node
order kept, so face and edge tags hold) and in set node lists, moves a vertex
tag to an untagged survivor, and refuses a merge that would collapse an
element. fieldcraft_mesh::join::coincident_nodes / merge_coincident find the
nodes within a distance of a lower-labelled survivor, deterministically.
Meshing cell by cell and mirroring use them; node merging commands will too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:50:37 -04:00
jyvikoandClaude Opus 5.5 f6d227d8cb UI: datum planes and axes in the viewport, datums and partitions in the browser
Datum planes draw as a hatched square around the model, axes as a line through
it, each with its name, in the desktop viewport and the headless render. The
browser's Geometry node lists the datums and the partitions with the datum
each cuts by.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:37:37 -04:00
jyvikoandClaude Opus 5.5 22f1006f71 Surface: close T-junctions left by independently tessellated faces
A face boundary vertex lying (within the weld distance) on an undivided edge of
the neighbouring face splits that edge's triangle. Only edges no other triangle
uses are looked at, so closed surfaces are unchanged. The half of a crank arm
cut on its symmetry plane tessellates with such a junction where the cut face
meets the top face; it now meshes (tet and swept hex).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:37:37 -04:00
jyvikoandClaude Opus 5.5 1c16972cf2 Engine: geometry.datum, geometry.datum.axis and geometry.partition
Datum planes by principal plane and offset, three points, or point and
normal; datum axes by principal axis, two points, or point and direction.
geometry.partition cuts the open design by a datum plane and keeps the
partition in the model, so geometry.open, file.open and undo cut the design
again. Requirements, forms and the Prepare entries are wired; features.md
lists them as ready.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:37:37 -04:00
jyvikoandClaude Opus 5.5 b0d0fc9900 Model: datum planes and axes, and partitions by datum plane
Datums are named planes (point, unit normal) and axes (point, unit direction);
a partition names the datum plane that cuts and, optionally, the bodies. A
datum a partition uses cannot be deleted or turned into an axis. Both are
stored in model.json, partitions in the order they cut.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:37:37 -04:00
jyvikoandClaude Opus 5.5 321add294b Geometry: partition a design's bodies by planes, with paired cut-face names
Design::partitioned cuts the bodies as opened by planes in order (SolidCraft's
split_by_plane, in memory). Cells are <body>/a and <body>/b by side of the plane;
the two faces of each cut are partition:<name>:a and :b, and every other face
inherits the name of the face it is a piece of (<name>#k when a cell holds
several pieces). A cut that misses or names an unknown body is reported as a
design error, not fatal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:37:37 -04:00
jyvikoandClaude Opus 5.5 4c91f9b731 deps: move the SolidCraft pin to a629236 (main, 2026-10-14)
Moves every solidcraft-* rev and the truck/egui-wgpu patches (same list upstream) from
de1479029dd6 to a629236650c4. Extrude gained a 'thin' option; the sample plate keeps a
solid extrude (thin: None). THIRD-PARTY-LICENSES.txt regenerated (solidcraft 0.8.0 -> 0.11.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 19:05:38 -04:00
jyvikoandClaude Opus 5.5 8409101483 UI: grey ribbon entries, search results and Solve that miss what they need
The ribbon buttons, drop-down rows, command search and the title bar's Solve read
Session::availability: greyed, with what is missing (and where to get it) in the tooltip.
Starting such an entry opens no form; the status bar names what is missing. ui.toolbar
reports each entry's `enabled` and `unavailable`, ui.inspect the Solve button's.

Fixes #220

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:43:29 -04:00
jyvikoandClaude Opus 5.5 e0d5adba23 Engine: each command lists what it needs, and execute checks it first
CommandSpec gains `requires: &[Requirement]` (crates/engine/src/requirement.rs): an open
design, geometry, nodes, a mesh, something to analyse, materials and sections for the
elements, sets, the definition an edit or delete acts on, a step, a result. Session::execute
checks them before running, so a command missing one fails at once with no partial work,
naming each missing piece and the toolbar entry that provides it ("Needs a material —
Properties › Material"). Requirements are real prerequisites (the model's own reference
checks and model.check's rules), never a workflow order. engine.commands / list_commands
list them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:43:29 -04:00
jyvikoandClaude Opus 5.5 06b98f01c7 Undo: a new model is untitled, and undoing it brings the old file back (#214)
geometry.open with "model": "new" cleared the model but kept the session's
file path, so File > Save wrote the new model over the previous one. The path
and the revision saved there (which document the session is) were not part of
the undo state. A step now records the document when its command changed it:
the new model is untitled and unsaved; undo restores the old file and its
clean state, redo the untitled model (or the file it was saved to since).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:25:09 -04:00
jyvikoandClaude Opus 5.5 2188d891ff Test: text typed into one form never lands in the next
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:16:25 -04:00
jyvikoandClaude Opus 5.5 1fc9d1e8d5 Form widgets carry ids scoped by the form's opening and field path
A form's text fields had positional egui ids, so focus and typed text moved to the
field at the same place in the next form (#219).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:16:25 -04:00
jyvikoandClaude Opus 5.5 94a10a1bf3 Open a design of another part: ask whether to start a new model
Opening (File > Open, a drop, the recent list) a design that has none of the
bodies the model's mesh and sets are on now asks, like the unsaved-changes
prompt: Start a new model with this design (default, Enter), Keep the
current model (the status names what no longer resolves), or Cancel. The
opened session waits for the answer; the same design opens without asking.
ui.inspect shows the prompt as {"design": path}; ui.prompt answers it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:07:30 -04:00
jyvikoandClaude Opus 5.5 14e2d25e68 MCP open: pass a design's model choice to geometry.open
The open tool's schema and description name the keep/new choice and the
reply's related/stale report; docs/mcp.md says the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:07:30 -04:00
jyvikoandClaude Opus 5.5 4a60674530 geometry.open: choose to keep the model or start a new one, and report what is stale
Opening a design over a model kept its mesh and every definition silently,
even when the design was another part (#145, #114). geometry.open now takes
`model`: "keep" (default: same-design reopen keeps the mesh and sets that
follow persistent face names) or "new" (clears mesh, definitions and
imported surfaces, keeps the unit system). The reply says whether the design
is `related` to the model's geometry references and lists `stale` mesh
bodies and sets. One undo step either way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 18:07:30 -04:00
jyvikoandClaude Opus 5.5 ddde08fb4c Results view: hover over contours is an outline, not a pink fill (#207)
While result contours are shown, the hovered item's face fill is left out
and only its outline, edges and nodes are drawn, so the hover never hides
the colours under the pointer. Picker::hover is the hover's own overlay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 17:53:46 -04:00
jyvikoandClaude Opus 5.5 a8f6be3bee docs: examples gallery as an even grid
A Markdown table sizes its columns by the captions, so the pictures came out
at different sizes; an HTML table with a third of the width per cell keeps
them even. The crank-arm picture is scaled to 1400x860 like the others, and
flow-past (no picture yet) moves to the end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 17:46:19 -04:00
jyvikoandClaude Opus 5.5 872dfdb421 release: check the licences in the installed package's file list
The Ubuntu and Fedora container images skip documentation when installing, so
the file is missing on disk even though the package carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 17:25:34 -04:00
jyvikoandClaude Opus 5.5 854ced2888 release: a Maintainer address the .deb accepts; no Debian changelog for an upstream package
lintian rejected the Maintainer field without an e-mail address, and the missing
changelog of a package built upstream rather than by a distribution.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 17:25:34 -04:00
jyvikoandClaude Opus 5.5 c8bd641e27 release: Linux .deb and .rpm packages (#125)
cargo-deb and cargo-generate-rpm (pinned) package the same stripped binaries and files as the
tar.gz under /usr. The release job compares the file lists, runs lintian, and installs both
packages in Ubuntu 22.04 and Fedora containers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 17:25:34 -04:00
jyvikoandClaude Opus 5.5 48cae3eb1d engine: heated-bracket test allows the clamped bore's 2.1 % on Linux
The heavy test asked the upright's top to grow within 2 % of free thermal
expansion; the clamped bore holds it back by 2.1 % on the Linux CI's tet mesh,
which differs from macOS's (#115). 3 % still catches a wrong expansion
coefficient or temperature.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:54:01 -04:00
jyvikoandClaude Opus 5.5 227c4544ed solver: mortar contact in 2D models
Plane strain, plane stress and axisymmetric models take contact pairs and
general (self) contact on the linear edges of tri3 and quad4 elements:
edges oriented out of their elements, the edge mortar of fem with the
thickness or 2 pi r in the weights, the element's area over the edge's
length as the thickness under it, and the in-plane rows of the tangent
blocks. Verified by the contact patch test in plane strain and
axisymmetric (to 1e-9 small sliding, 1e-4 finite), Hertz's line contact
on quad4 edges (Johnson 1985, 4.3; equal to the hex8 model's to 1e-5),
and a hybrid rubber C-ring closing on itself that moves node for node as
the one-layer solid ring.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:30:44 -04:00
jyvikoandClaude Opus 5.5 6baa189231 fem: hybrid plane strain and axisymmetric elements
One constant pressure per element (mean dilatation, Nagtegaal, Parks &
Rice 1974; the hoop strain in the divergence) for quad4, quad8 and tri6:
the linear stiffness, stresses and thermal load, and the finite- and
small-strain forms of nonlinear steps with their consistent tangent. The
linear triangle and plane stress are refused by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:30:44 -04:00
jyvikoandClaude Opus 5.5 2ca5f84113 model: exterior edges of 2D elements
The boundary of a 2D model, which general contact takes by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:30:44 -04:00
jyvikoandClaude Opus 5.5 6da3055a1c fem: mortar integration over the edges of 2D models
Segment-to-segment overlap of two edges projected along the secondary
normal (Yang, Laursen & Meng 2005), three-point Gauss-Legendre with the
out-of-plane measure (thickness or 2 pi r) in the weight, over the same
Real scalars as faces so the solver gets exact derivatives.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:30:44 -04:00
jyvikoandClaude Opus 5.5 6bd52c0b29 engine: crank-arm sample, a bicycle crank swept all-hex and solved
file.sample crank-arm: a 170 mm 6061-T6 crank built in SolidCraft
(crates/engine/samples/crank-arm.json), swept along z by mesh.hex.generate
as 7274 hex20 elements of 3 mm (scaled Jacobian min 0.17). The hex variant
drops the pocket floor fillet and boss chamfers, and its root arcs meet the
bosses 20 degrees off tangent so the arm's top face has no zero-angle cusp.
The square bore is fixed and 1500 N acts on the pedal hole; the faces are
picked by their surfaces, not their names. Its heavy test matches the root
bending stress to M/Z = 62.6 MPa within 3 % (0.3 % in practice).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 16:20:35 -04:00
jyvikoandClaude Opus 5.5 98d263ae54 docs: examples gallery in the README
An Examples section before Build: a tile per sample with its picture, one
line and its name for File > Samples or fieldcraft --sample NAME, linking
docs/examples.md; the roadmap notes the gallery.

Closes #167

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 0b7f3021d9 engine: bracket-hex sample, the partitioned bracket meshed all-hex and solved
file.sample bracket-hex: the corpus bracket split into 30 SolidCraft cells,
meshed by mesh.hex.blocks as one conforming hex20 mesh of 3 mm, clamped at
the upright and loaded at the foot. The sample's script finds the clamp and
load faces in every cell that has them. Its test matches the tip deflection
of a fine tet10 solution within 1 % and checks the clamp carries the load.

Closes #166

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 f5a0a1289a engine: heated-bracket sample, steady heat and thermal stress in steel
file.sample heated-bracket: the corpus filleted bracket in steel, tet10, its
hole bores clamped, the upright's end held at 120 C and the rest cooled by
still air; one coupled temperature-displacement step. Its test checks the
temperatures against the heater and the air, then warms the bracket evenly,
clamps one hole, and matches the free thermal expansion alpha dT times the
distance from the hole along x.

Closes #165

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 ecdff11e72 engine: flow-past sample, air past an L-bracket on the floor
file.sample flow-past: air at 25 mm/s past the upright L-bracket in a box of
2.5 mm lattice cells (Re 83), inlet, outlet, a no-slip floor and slip walls;
the fluid step reports the force on each named face. Its test holds the
drag coefficient on the upright's frontal area between 1 and 3.5 (2.3) and
the lattice's mass change under 1 %. No picture: the viewport does not draw
flow results yet (M12).

Part of #164 (its streamlines wait for a flow display in the viewport)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 cf8ed71e4f engine: rubber-seal sample, a Mooney-Rivlin gasket ring squeezed 25 %
file.sample rubber-seal: a gasket ring of hybrid hex8 elements in four
mapped quarter blocks, squeezed 2.5 mm between plates bonded to it
(nonlinear static, Mooney-Rivlin rubber). Its test frees the plates and
matches the closed form for incompressible uniaxial compression within 3 %,
and bounds the bonded ring's extra stiffness. The plates are prescribed
displacements until implicit contact (#161) can press it into a groove.

Closes #163

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 581646bdac engine: drop-test sample, an aluminium bracket dropped onto a tilted floor
file.sample drop-test: an L-bracket standing on its foot (a SolidCraft script
in sample.rs) swept into hex8, falling 2 m onto a rigid floor tilted 15 deg;
explicit dynamics for 1 ms with gravity and plasticity. Its test checks the
mass against rho V, the impact speed sqrt(2 g h) and kinetic energy, the
energy balance and the momentum the floor takes. docs/examples.md starts
with it, and its picture is docs/media/examples/drop-test.png.

Closes #162

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 c9a765aa02 engine: samples can build their geometry from a SolidCraft script
A sample may carry a SolidCraft script (the corpus recipe form) whose design
opens before its commands run, and its script sees the design's bodies.
fieldcraft-engine now builds fieldcraft-geometry with its scripts feature.
The start screen scrolls its sample list, and a test keeps the file.sample
form's choices in step with the samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:55:22 -04:00
jyvikoandClaude Opus 5.5 0220e2d8bb engine, docs: self-contact in nonlinear static steps
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:47:17 -04:00
jyvikoandClaude Opus 5.5 85f0905db1 solver: single-surface (self) contact in nonlinear static steps
General contact, on a set's faces or every exterior face of the solids, is mortar contact
with one face list as both sides: each face against every other one that faces it, shares no
node with its element and is not reached through more than half an element, paired both
ways. Tested by a nearly incompressible Mooney-Rivlin C-ring (hybrid hex8) closing on itself
(no penetration beyond the mortar's weak enforcement, mirror symmetry to 1e-6) and, heavy, a
rubber bellows whose folds press on each other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:47:17 -04:00
jyvikoandClaude Opus 5.5 2b1c52d021 verification: the tie patch test
An oracle case of uniaxial tension across a tie of non-matching meshes; the tie formulation
in docs/fem.md and the literature survey; ROADMAP M7 and parity updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:28:02 -04:00
jyvikoandClaude Opus 5.5 794aa9f158 decks: ties as Abaqus *TIE and LS-DYNA tied contact
Nastran refuses them by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:28:02 -04:00
jyvikoandClaude Opus 5.5 7e9366f726 engine: interaction.tie, tie.edit and tie.delete
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:28:02 -04:00
jyvikoandClaude Opus 5.5 f9981d305e solver: ties by dual mortar constraints
Each secondary node follows the main surface under it as the weighted average
u_A = sum_J (M_AJ / sum_K M_AK) u_J with M_AJ = int psi_A N_J over the reference overlaps and
psi the secondary faces' dual shape functions (Wohlmuth 2000), so the secondary mortar
matrix is diagonal; the rows join the couplings' constraint elimination in every implicit
analysis. Uncovered secondary nodes stay free with a warning; heat transfer and explicit
dynamics refuse ties by name. Tested by the tie patch test on non-matching hex8/tet4 meshes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:28:02 -04:00
jyvikoandClaude Opus 5.5 8d2fa980a5 model: ties between surfaces
A tie names a main and a secondary face set and an optional position tolerance; it refers to
its sets, round-trips, is bounded in number and checked for solid faces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:28:02 -04:00
jyvikoandClaude Opus 5.5 a91ac5baf9 verification: Coulomb friction between sliding blocks
An oracle case of a block pressed on another and slid with static and kinetic coefficients
(mu_k N carried once slipping), and the docs of the friction formulation; ROADMAP M7 and
parity updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:14:14 -04:00
jyvikoandClaude Opus 5.5 32c5c1b307 engine: friction output of implicit contact
solve.nonlinear counts the slipping nodes, solve.probe gives a secondary node's shear traction
and slip, and the results display draws contact_shear and contact_slip, contact_status coding
stick and slip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:14:14 -04:00
jyvikoandClaude Opus 5.5 6ca3233aaa solver: Coulomb friction for implicit mortar contact
A return map at the closed secondary nodes on the mortar slip in its rate form (w_A = B_A dx,
B_A = [int Phi_A N_i P, -int Phi_A N_j P]): stick within mu p_A, slip back to the cone, static
coefficient for a node that stuck in the last increment and kinetic for one that slipped; the
friction does the virtual work t . B_A dx, so a slipping interface carries mu N exactly. The
tangent is symmetrised (stick and slip stiffness kept, the coupling to the pressure and the
change of B left out; the residual is exact). Tractions and slip states are committed with the
converged increment. After a chattering cutback, nodes open by less than 1e-3 of their
element's thickness keep their penalty in the tangent for the rest of the step. Results carry
the shear traction, the slip and stick/slip status.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 15:14:14 -04:00
jyvikoandClaude Opus 5.5 945a2076c3 verification: implicit contact patch test and Hertz line contact
Two oracle cases: the contact patch test on non-matching meshes in small and finite sliding,
and Hertz's cylinder on a flat under force control (peak pressure, pressure distribution,
subsurface stress). docs/fem.md describes the formulation, the literature survey its papers;
ROADMAP M7 and parity are updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 14:58:32 -04:00
jyvikoandClaude Opus 5.5 5770288f47 engine: contact output of nonlinear static steps
solve.nonlinear summarises each contact (normal force, largest pressure, closed nodes, deepest
penetration, augmentations), solve.probe gives a secondary node's pressure, gap and status per
contact, and the results display draws contact_pressure, contact_gap and contact_status. The
contact commands, the catalogue and the model docs say what nonlinear static steps do with a
pair.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 14:58:32 -04:00
jyvikoandClaude Opus 5.5 8871f6721d solver: mortar contact in nonlinear static steps
Frictionless contact pairs enforced by an augmented Lagrangian: nodal pressures from the
mortar weighted gaps, Uzawa updates after each converged increment until the gaps are within
1e-5 of the element thickness, and the consistent tangent (outer products of the weighted
gap gradients and the pressure-weighted Hessians from the automatic differentiation of the
mortar integrals). Finite sliding searches and integrates on the current configuration every
evaluation; without nonlinear geometry the pairs and their mortar integrals are fixed in the
reference configuration (small sliding, linear and exact). The tangent's pattern takes the
face pairs' blocks; the step cuts back when the active set chatters. Initial overclosure is
offset or refused; general contact, 2D models and arc length are refused by name; the linear
analyses refuse contact by name instead of the mesh.

With contact the convergence force scale comes from the converged states, the loads and the
current state. The loads-and-reactions balance check takes the nodal reactions into its scale
(no spurious warning for a part squeezed between held faces).

Tests: the contact patch test on non-matching hex8/tet4 meshes (exact with small sliding,
to 1e-4 with finite sliding), Hertz cylinder on a flat (peak pressure within 3%, half-width
bracketed) with quadratic Newton convergence, overclosure, thread-count determinism and the
refusals; Hertz sphere on a flat (heavy).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 14:58:32 -04:00
jyvikoandClaude Opus 5.5 37f338c9e8 fem: mortar segmentation of face pairs with forward-mode automatic differentiation
The overlap of a secondary face with a main face (projection onto the secondary plane,
Sutherland-Hodgman clipping of their triangles, Radon's seven-point rule on the overlap's
fan) and the inverse linear and bilinear maps of both faces, written over a Real scalar so
that f64, Dual (gradient) and Hyper (gradient and packed Hessian, 24 variables) give the
values and the exact linearisation of the segmentation, the normal and the projection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UhhZMBTviDQxZvwnyP89fo
2026-10-14 14:58:32 -04:00
269 changed files with 34788 additions and 2114 deletions

No files matched your search

+1 -1
View File
@@ -41,6 +41,6 @@ body:
id: version
attributes:
label: Version and platform
placeholder: "v0.5.7 (or commit), macOS 15 arm64"
placeholder: "v0.5.9 (or commit), macOS 15 arm64"
validations:
required: true
+2
View File
@@ -21,6 +21,8 @@ modal problems with its own solver. AI agents can drive it over MCP (`fieldcraft
To start with a sample model, run the app with `--sample cantilever` (macOS:
`/Applications/FieldCraft.app/Contents/MacOS/FieldCraft --sample cantilever`).
**Updates.** {update_signing}
**Signing.** {macos_signing} The Linux and Windows builds are not signed; on Windows, SmartScreen
may say "Windows protected your PC": choose **More info**, then **Run anyway**.
+4
View File
@@ -53,6 +53,10 @@ jobs:
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: Build the web app
working-directory: apps/fieldcraft-web
env:
# Usage analytics only in the deployed build (main), and only with the user's consent
# (docs/privacy.md); develop builds get an empty key, which sends nothing.
FIELDCRAFT_POSTHOG_KEY: ${{ github.ref == 'refs/heads/main' && secrets.POSTHOG_KEY || '' }}
run: trunk build --release --public-url /fieldcraft/
- name: Bundle size
run: |
+90 -8
View File
@@ -3,13 +3,14 @@
#
# A push to `main` (fast-forwarded from a verified `develop` commit; main holds released code only)
# builds every package and creates or updates the
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt and generated notes. The
# DRAFT GitHub Release "FieldCraft v<version>", with SHA256SUMS.txt (signed with the release key
# into SHA256SUMS.txt.minisig when the FIELDCRAFT_SIGNING_KEY secret exists) and generated notes. The
# version is [workspace.package] version in Cargo.toml; a suffix (0.2.0-rc.1) makes a
# pre-release. A person verifies the draft and publishes it; this workflow never publishes,
# and pushes to develop or tags never start it.
#
# macOS universal (arm64 + x86_64) .dmg with FieldCraft.app, the CLI as a .zip packaging/macos
# Linux x86_64 (glibc 2.35+) .tar.gz and .AppImage packaging/linux
# Linux x86_64 (glibc 2.35+) .tar.gz, .AppImage, .deb and .rpm packaging/linux
# Windows x64 .zip with fieldcraft.exe and fieldcraft-cli.exe packaging/windows
#
# macOS: signed with a Developer ID and notarized when the APPLE_* secrets exist, ad-hoc
@@ -97,6 +98,8 @@ jobs:
- name: Build, sign, notarize and package (the dmg is mounted and checked)
id: package
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
@@ -119,33 +122,76 @@ jobs:
timeout-minutes: 90
env:
FIELDCRAFT_VERSION: ${{ needs.version.outputs.version }}
# The .deb and .rpm builders (both MIT), pinned.
CARGO_DEB_VERSION: 3.8.0
CARGO_GENERATE_RPM_VERSION: 0.21.0
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends desktop-file-utils
sudo apt-get install -y --no-install-recommends desktop-file-utils lintian rpm
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-linux-x86_64
# Release runs are rare: only release-branch runs keep a cache, so dry runs don't evict CI's.
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Build and package (tar.gz, AppImage)
- name: Install cargo-deb and cargo-generate-rpm
run: |
cargo install --locked --version "$CARGO_DEB_VERSION" cargo-deb
cargo install --locked --version "$CARGO_GENERATE_RPM_VERSION" cargo-generate-rpm
- name: Build and package (tar.gz, AppImage, deb, rpm)
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
run: packaging/linux/package.sh
- name: Check the packages
run: |
. packaging/env.sh
list="$(tar -tzf dist/release/*.tar.gz)"
base="fieldcraft-$VERSION-linux-x86_64"
deb="dist/release/fieldcraft_${VERSION}_amd64.deb"
rpm="dist/release/fieldcraft-$VERSION.x86_64.rpm"
list="$(tar -tzf "dist/release/$base.tar.gz")"
for f in bin/fieldcraft bin/fieldcraft-cli "share/applications/$APP_ID.desktop" \
share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt; do
grep -Fx -- "fieldcraft-$VERSION-linux-x86_64/$f" <<<"$list"
grep -Fx -- "$base/$f" <<<"$list"
done
# The .deb and .rpm carry the tar.gz's files under /usr (the .deb adds its copyright
# file); their lists live in apps/fieldcraft/Cargo.toml, so a drift fails here.
files() { grep -v '/$' | sed -E "s#^(\./|/|$base/)##; s#^usr/##" | grep -vx 'share/doc/fieldcraft/copyright' | sort; }
diff <(files <<<"$list") <(dpkg-deb --fsys-tarfile "$deb" | tar -t | files)
diff <(files <<<"$list") <(rpm -qpl "$rpm" | files)
dpkg-deb --info "$deb"
rpm -qpi "$rpm"
echo "rpm requires:"; rpm -qpR "$rpm"
# The release notes live on GitHub, so the package has no Debian changelog (a native
# package built upstream, not by a distribution).
lintian --info --fail-on error --suppress-tags no-changelog "$deb"
ldd target/release/fieldcraft
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
done
- name: Install the .deb and .rpm in containers
run: |
# The oldest supported Ubuntu (the build's glibc) and a current Fedora. Recommended and
# weak dependencies (GPU drivers) are skipped to keep it quick; the hard ones must resolve.
# Both images leave out documentation when installing (dpkg path-exclude, dnf nodocs), so
# the licences are checked in the package's file list rather than on disk.
docker run --rm -v "$PWD/dist/release:/dist:ro" ubuntu:22.04 bash -euxc '
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends /dist/*.deb
fieldcraft-cli --version
fieldcraft --version
dpkg -L fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt'
docker run --rm -v "$PWD/dist/release:/dist:ro" fedora:44 bash -euxc '
dnf install -y -q --setopt=install_weak_deps=False /dist/*.rpm
fieldcraft-cli --version
fieldcraft --version
rpm -ql fieldcraft | grep -Fx /usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt
dnf install -y -q rpmlint
rpmlint /dist/*.rpm || true'
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-linux-x86_64
@@ -171,6 +217,9 @@ jobs:
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Build and package (zip)
shell: pwsh
env:
# The analytics project key (docs/privacy.md), built in; never printed.
FIELDCRAFT_POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}
run: ./packaging/windows/package.ps1
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -197,21 +246,54 @@ jobs:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Check the set, checksums and notes
- name: Check the set and write the checksums
run: |
for f in "fieldcraft-$VERSION-macos-universal.dmg" "fieldcraft-cli-$VERSION-macos-universal.zip" \
"fieldcraft-$VERSION-linux-x86_64.tar.gz" "fieldcraft-$VERSION-linux-x86_64.AppImage" \
"fieldcraft_${VERSION}_amd64.deb" "fieldcraft-$VERSION.x86_64.rpm" \
"fieldcraft-$VERSION-windows-x64.zip"; do
test -s "artifacts/$f" || { echo "::error::missing $f"; exit 1; }
done
(cd artifacts && sha256sum -- * | tee SHA256SUMS.txt)
- name: Sign SHA256SUMS.txt with the release key (skipped without FIELDCRAFT_SIGNING_KEY)
id: sign
env:
FIELDCRAFT_SIGNING_KEY: ${{ secrets.FIELDCRAFT_SIGNING_KEY }}
# rsign2 (MIT), a minisign-compatible signer, pinned.
RSIGN_VERSION: 0.6.7
run: |
if [ -z "$FIELDCRAFT_SIGNING_KEY" ]; then
echo "::warning::FIELDCRAFT_SIGNING_KEY is not set: SHA256SUMS.txt is not signed, so the app cannot install this release itself (docs/releasing.md)"
echo "signed=false" >>"$GITHUB_OUTPUT"
exit 0
fi
cargo install --locked --quiet --root "$RUNNER_TEMP/rsign" rsign2 --version "$RSIGN_VERSION"
rsign="$RUNNER_TEMP/rsign/bin/rsign"
key="$RUNNER_TEMP/release.key"
(umask 077 && printf '%s\n' "$FIELDCRAFT_SIGNING_KEY" >"$key")
"$rsign" sign -W -s "$key" -t "FieldCraft v$VERSION SHA256SUMS.txt" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
rm -f "$key"
# The signature must verify with the public key the app is built with.
public="$(sed -n 's/^pub const PUBLIC_KEY: &str = "\(.*\)";$/\1/p' crates/update/src/lib.rs)"
"$rsign" verify -q -P "$public" -x artifacts/SHA256SUMS.txt.minisig artifacts/SHA256SUMS.txt
echo "signed=true" >>"$GITHUB_OUTPUT"
- name: Write the notes
env:
SIGNED: ${{ steps.sign.outputs.signed }}
run: |
# The macOS paragraph says how the app was signed (packaging/macos/package.sh).
case "$MACOS_SIGNING" in
notarized) macos="The macOS app is signed with a Developer ID and notarized by Apple." ;;
signed) macos="The macOS app is signed with a Developer ID but **not notarized**: the first time, right-click \`FieldCraft.app\` in Applications and choose **Open**." ;;
*) macos="The macOS app is **ad-hoc signed and not notarized**: macOS blocks the first launch. Right-click \`FieldCraft.app\` in Applications and choose **Open** (then **Open** again), or run \`xattr -dr com.apple.quarantine /Applications/FieldCraft.app\`." ;;
esac
awk -v v="$VERSION" -v m="$macos" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); print }' \
# The updates paragraph says whether the app can install this release itself.
if [ "$SIGNED" = true ]; then
updates="\`SHA256SUMS.txt\` is signed with the FieldCraft release key (\`SHA256SUMS.txt.minisig\`), so FieldCraft's Help › Check for Updates can verify and install this release."
else
updates="This release's \`SHA256SUMS.txt\` is **not signed**: FieldCraft's in-app updates can't verify it and won't install it; download it from this page instead."
fi
awk -v v="$VERSION" -v m="$macos" -v u="$updates" '{ gsub(/\{version\}/, v); gsub(/\{macos_signing\}/, m); gsub(/\{update_signing\}/, u); print }' \
.github/release-notes.md >notes.md
cat notes.md >>"$GITHUB_STEP_SUMMARY"
- name: Upload the dry-run artifacts
+22 -4
View File
@@ -18,12 +18,25 @@ is committed and listed here with its exports.
| docs/media/ibeam-analysis.mp4, docs/media/ibeam-analysis.gif | FieldCraft contributors | Original: the FieldCraft window captured during an MCP session, generated by `tools/demo-video/make.py` | MIT OR Apache-2.0 |
| docs/media/og.svg, docs/media/og.png | FieldCraft contributors | Original social-preview image (1280 × 640): the application icon's cube layer (assets/app-icon/FieldCraft.icon/Assets/02-part.svg) beside the name and tagline set in Inter (OFL, crates/ui-egui/fonts) | MIT OR Apache-2.0 |
| docs/media/bracket-partition.png, docs/media/bracket-hex.png, docs/media/bracket-stress.png, docs/media/setup-symbols.png | FieldCraft contributors | Original: FieldCraft renders (headless MCP screenshots and a window capture) of corpus parts and the cantilever sample | MIT OR Apache-2.0 |
| docs/media/examples/drop-test.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved drop-test sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/rubber-seal.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved rubber-seal sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/heated-bracket.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved heated-bracket sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/bracket-hex.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved bracket-hex sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/crank-arm.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-arm sample (docs/examples.md) | MIT OR Apache-2.0 |
| docs/media/examples/crank-mirror.png | FieldCraft contributors | Original: the FieldCraft window captured (`ui.capture`) with the solved crank-mirror sample (docs/examples.md) | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/bracket-hex.png | FieldCraft contributors | Original: the viewport of docs/media/examples/bracket-hex.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the bracket-hex sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/crank-arm.png | FieldCraft contributors | Original: the viewport of docs/media/examples/crank-arm.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-arm sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/crank-mirror.png | FieldCraft contributors | Original: the viewport of docs/media/examples/crank-mirror.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the crank-mirror sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/drop-test.png | FieldCraft contributors | Original: the viewport of docs/media/examples/drop-test.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the drop-test sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/heated-bracket.png | FieldCraft contributors | Original: the viewport of docs/media/examples/heated-bracket.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the heated-bracket sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/ui-egui/thumbnails/rubber-seal.png | FieldCraft contributors | Original: the viewport of docs/media/examples/rubber-seal.png cropped to the model and scaled to 320 px wide (ImageMagick, 128-colour palette), the rubber-seal sample's thumbnail on the Start card | MIT OR Apache-2.0 |
| crates/decks/tests/golden/nastran/*.bdf | FieldCraft contributors | Written by our Nastran writer from our own test models (crates/decks/tests/nastran.rs) | MIT OR Apache-2.0 |
| assets/icons/assembly.instance.svg, assets/icons/assembly.instance.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/assembly.instance.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.read.svg, assets/icons/deck.read.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.read.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.abaqus.svg, assets/icons/deck.write.abaqus.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.abaqus.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.lsdyna.svg, assets/icons/deck.write.lsdyna.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.lsdyna.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/deck.write.nastran.svg, assets/icons/deck.write.nastran.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/deck.write.nastran.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/diagnostics.bug_report.svg, assets/icons/diagnostics.bug_report.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/diagnostics.bug_report.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/edit.redo.svg, assets/icons/edit.redo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.redo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/edit.undo.svg, assets/icons/edit.undo.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/edit.undo.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/file.open.svg, assets/icons/file.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -32,6 +45,8 @@ is committed and listed here with its exports.
| assets/icons/file.save.svg, assets/icons/file.save.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/file.save.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.bodies.svg, assets/icons/geometry.bodies.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.bodies.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.svg, assets/icons/geometry.datum.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.axis.svg, assets/icons/geometry.datum.axis.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.axis.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.datum.point.svg, assets/icons/geometry.datum.point.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.datum.point.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.import.mesh.svg, assets/icons/geometry.import.mesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.import.mesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.midsurface.svg, assets/icons/geometry.midsurface.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.midsurface.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/geometry.open.svg, assets/icons/geometry.open.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/geometry.open.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -51,11 +66,10 @@ is committed and listed here with its exports.
| assets/icons/mesh.element.add.svg, assets/icons/mesh.element.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.element.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.decompose.svg, assets/icons/mesh.hex.decompose.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.decompose.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.dominant.svg, assets/icons/mesh.hex.dominant.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.dominant.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.blocks.svg, assets/icons/mesh.hex.blocks.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.blocks.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.mapped.svg, assets/icons/mesh.hex.mapped.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.mapped.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.cells.svg, assets/icons/mesh.cells.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.cells.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.generate.svg, assets/icons/mesh.hex.generate.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.generate.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.octree.svg, assets/icons/mesh.hex.octree.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.octree.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.polycube.svg, assets/icons/mesh.hex.polycube.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.polycube.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.hex.sweep.svg, assets/icons/mesh.hex.sweep.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.hex.sweep.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.import.orphan.svg, assets/icons/mesh.import.orphan.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.import.orphan.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.layers.svg, assets/icons/mesh.layers.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.layers.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.node.add.svg, assets/icons/mesh.node.add.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.node.add.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -66,7 +80,7 @@ is committed and listed here with its exports.
| assets/icons/mesh.region.remesh.svg, assets/icons/mesh.region.remesh.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.region.remesh.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.size.adapt.svg, assets/icons/mesh.size.adapt.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.adapt.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.size.global.svg, assets/icons/mesh.size.global.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.global.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.size.seed.svg, assets/icons/mesh.size.seed.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.size.seed.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.seed.edge.svg, assets/icons/mesh.seed.edge.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.seed.edge.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.smooth.svg, assets/icons/mesh.smooth.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.smooth.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.surface.check.svg, assets/icons/mesh.surface.check.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.surface.check.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/mesh.tag.svg, assets/icons/mesh.tag.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/mesh.tag.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
@@ -136,6 +150,7 @@ is committed and listed here with its exports.
| assets/icons/ui.sun.svg, assets/icons/ui.sun.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.sun.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/ui.views.svg, assets/icons/ui.views.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.views.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/ui.zoom.svg, assets/icons/ui.zoom.vectorcraft | FieldCraft contributors | Original interface icon (navigation bar, title bar, browser) drawn with VectorCraft from `assets/icons/src/ui.zoom.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/icons/view.show_all.svg, assets/icons/view.show_all.vectorcraft | FieldCraft contributors | Original toolbar icon drawn with VectorCraft from `assets/icons/src/view.show_all.json` (`cargo xtask icons`) | MIT OR Apache-2.0 |
| assets/app-icon/icon.vectorcraft, assets/app-icon/icon.svg, assets/app-icon/icon.png | FieldCraft contributors | Original application icon (a hexahedral-meshed cube with a banded colour fringe on its faces on a rounded-square backdrop), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs); editable source, SVG and 1024 × 1024 PNG export | MIT OR Apache-2.0 |
| assets/app-icon/icon-small.vectorcraft, assets/app-icon/icon-small.svg, assets/app-icon/icon-small.png | FieldCraft contributors | Original simplified application icon for 16–32 px (the fringe cube alone; no mesh or floor grid), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
| assets/app-icon/layers/01-floor.vectorcraft, assets/app-icon/FieldCraft.icon/Assets/01-floor.svg | FieldCraft contributors | Original isometric floor grid with a radial fade (Default appearance), drawn with VectorCraft by `cargo xtask app-icon` (xtask/src/app_icon.rs) | MIT OR Apache-2.0 |
@@ -168,13 +183,16 @@ is committed and listed here with its exports.
| crates/geometry/src/tagged_mesh.rs (package and part reading, transforms, units, caps) | SolidCraft `crates/io/src/threemf.rs` | MIT OR Apache-2.0 |
| crates/render/src/camera.rs, crates/render/src/raster.rs | SolidCraft `crates/render/src/camera.rs`, `raster.rs` | MIT OR Apache-2.0 |
| crates/ui-egui/src/gpu.rs, crates/ui-egui/src/theme.rs (tokens and their values), crates/ui-egui/src/control.rs, crates/ui-egui/src/lib.rs (input injection, screenshots), crates/ui-egui/src/toolbar.rs (workspace switcher, tabs, panels with drop-downs, fitting), crates/ui-egui/src/appbar.rs (application bar; the mark is drawn from assets/app-icon/icon-small.svg's coordinates), crates/ui-egui/src/titlebar.rs (caption buttons, drag and resize zones; SolidCraft took it from VectorCraft), crates/ui-egui/src/frame.rs (windows, heading bands), crates/ui-egui/src/browser.rs (row drawing), crates/ui-egui/src/palette.rs (command line and search), crates/ui-egui/src/timeline.rs (timeline strip, transport), crates/ui-egui/src/viewport.rs (navigation bar, orientation gizmo), crates/ui-egui/src/files.rs (background opening, file pickers as host services) | SolidCraft `crates/ui-egui/src/` (titlebar.rs also VectorCraft `crates/ui-egui/src/titlebar.rs`) | MIT OR Apache-2.0 |
| crates/ui-egui/src/navigation.rs (navigation presets and bindings), crates/ui-egui/src/viewport.rs (orbit about the point under the cursor, or the drawn centre from empty space; Ctrl + left drag orbits) | SolidCraft `crates/ui-egui/src/prefs.rs` (`NavPreset`, `NavBinding`, `NAV_PRESETS`, `orbit`) | MIT OR Apache-2.0 |
| crates/ui-egui/src/fields.rs (form rows: a label column of fixed width, then the field) | SolidCraft `crates/ui-egui/src/dialogs.rs` | MIT OR Apache-2.0 |
| crates/io/src/fs.rs (atomic writes) | SolidCraft `crates/io/src/safe_write.rs` | MIT OR Apache-2.0 |
| crates/io/src/recovery.rs (recovery folder, entries, locks) | SolidCraft `crates/engine/src/recovery.rs` | MIT OR Apache-2.0 |
| crates/engine/src/crash.rs, crates/engine/src/crash_tests.rs (crash reports: panic hook, locked command journal, unclean-exit detection, report folders and limits, replay), apps/fieldcraft-cli/src/crashes.rs, docs/crash-reports.md (structure) | SolidCraft `crates/engine/src/crash.rs`, `crash_tests.rs`, `apps/solidcraft-cli/src/crashes.rs`, `docs/crash-reports.md` | MIT OR Apache-2.0 |
| apps/fieldcraft/src/control_server.rs | SolidCraft `apps/solidcraft/src/control_server.rs` | MIT OR Apache-2.0 |
| crates/mcp/src/ (JSON-RPC framing, MCP lifecycle, tool schema checks, the control-channel backend, base64) | SolidCraft `crates/mcp/src/` | MIT OR Apache-2.0 |
| crates/io/src/roots.rs (the rules of read and write roots) | VectorCraft's automation roots (docs/mcp.md there) | MIT OR Apache-2.0 |
| packaging/env.sh, packaging/.shellcheckrc, packaging/macos/package.sh, packaging/macos/Info.plist.in, packaging/linux/package.sh, packaging/linux/AppRun, packaging/windows/package.ps1 | SolidCraft `packaging/` and VectorCraft `packaging/` (signing and notarization in macos/package.sh) | MIT OR Apache-2.0 |
| apps/fieldcraft/Cargo.toml (the run-time dependency lists of `[package.metadata.deb]` and `[package.metadata.generate-rpm]`) | SolidCraft `packaging/linux/nfpm.yaml` | MIT OR Apache-2.0 |
| packaging/macos/import-cert.sh | VectorCraft `packaging/macos/import-cert.sh` | MIT OR Apache-2.0 |
| packaging/windows/check-exe.ps1 | SolidCraft `packaging/windows/check-icon.ps1` | MIT OR Apache-2.0 |
| apps/fieldcraft-web/ (the web runner, browser file services and downloads, Trunk configuration, index.html) | VectorCraft `apps/vectorcraft-web/` and SolidCraft `apps/solidcraft-web/` | MIT OR Apache-2.0 |
Generated
+419 -43
View File
@@ -431,6 +431,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -661,6 +667,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common 0.1.7",
"inout",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -731,6 +747,16 @@ dependencies = [
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -744,7 +770,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics-types",
"foreign-types",
"libc",
@@ -757,7 +783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation 0.9.4",
"libc",
]
@@ -846,6 +872,12 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "ct-codecs"
version = "1.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd9f3db6f2cfef61c10613071955154ffdc9e515daebff26de4b54e35038fdd"
[[package]]
name = "cursor-icon"
version = "1.2.0"
@@ -890,6 +922,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer 0.10.4",
"crypto-common 0.1.7",
"subtle",
]
[[package]]
@@ -1019,7 +1052,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.36.2"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"ahash",
"bytemuck",
@@ -1237,7 +1270,7 @@ checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
[[package]]
name = "fieldcraft"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"eframe",
"egui",
@@ -1245,24 +1278,29 @@ dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
"fieldcraft-ui-egui",
"fieldcraft-update",
"getrandom 0.3.4",
"log",
"rfd",
"rustls",
"serde_json",
"ureq",
]
[[package]]
name = "fieldcraft-cli"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
"fieldcraft-mcp",
"fieldcraft-update",
"serde_json",
]
[[package]]
name = "fieldcraft-decks"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"serde_json",
@@ -1271,7 +1309,7 @@ dependencies = [
[[package]]
name = "fieldcraft-engine"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-decks",
"fieldcraft-explicit",
@@ -1284,7 +1322,9 @@ dependencies = [
"fieldcraft-parallel",
"fieldcraft-render",
"fieldcraft-solver",
"fieldcraft-update",
"log",
"png",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1293,7 +1333,7 @@ dependencies = [
[[package]]
name = "fieldcraft-explicit"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-fem",
"fieldcraft-model",
@@ -1304,7 +1344,7 @@ dependencies = [
[[package]]
name = "fieldcraft-fem"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"thiserror 2.0.21",
@@ -1312,7 +1352,7 @@ dependencies = [
[[package]]
name = "fieldcraft-geometry"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"quick-xml",
@@ -1328,7 +1368,7 @@ dependencies = [
[[package]]
name = "fieldcraft-io"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"log",
@@ -1341,7 +1381,7 @@ dependencies = [
[[package]]
name = "fieldcraft-lbm"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-mesh",
"fieldcraft-model",
@@ -1351,7 +1391,7 @@ dependencies = [
[[package]]
name = "fieldcraft-mcp"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-engine",
"fieldcraft-io",
@@ -1362,7 +1402,7 @@ dependencies = [
[[package]]
name = "fieldcraft-mesh"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"num-bigint",
@@ -1374,7 +1414,7 @@ dependencies = [
[[package]]
name = "fieldcraft-model"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"serde",
"serde_json",
@@ -1383,14 +1423,14 @@ dependencies = [
[[package]]
name = "fieldcraft-parallel"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"rayon",
]
[[package]]
name = "fieldcraft-render"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-model",
"png",
@@ -1400,7 +1440,7 @@ dependencies = [
[[package]]
name = "fieldcraft-solver"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-fem",
"fieldcraft-mesh",
@@ -1412,7 +1452,7 @@ dependencies = [
[[package]]
name = "fieldcraft-testkit"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"fieldcraft-engine",
"fieldcraft-geometry",
@@ -1423,7 +1463,7 @@ dependencies = [
[[package]]
name = "fieldcraft-ui-egui"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"craft-ui",
"egui",
@@ -1434,17 +1474,36 @@ dependencies = [
"fieldcraft-geometry",
"fieldcraft-model",
"fieldcraft-render",
"fieldcraft-update",
"log",
"png",
"resvg",
"serde",
"serde_json",
]
[[package]]
name = "fieldcraft-web"
version = "0.5.7"
name = "fieldcraft-update"
version = "0.5.9"
dependencies = [
"base64",
"flate2",
"log",
"minisign",
"minisign-verify",
"rustls",
"serde_json",
"sha2 0.11.1",
"tar",
"thiserror 2.0.21",
"ureq",
"zip",
]
[[package]]
name = "fieldcraft-web"
version = "0.5.9"
dependencies = [
"base64 0.22.1",
"eframe",
"egui",
"fieldcraft-engine",
@@ -1459,6 +1518,16 @@ dependencies = [
"web-sys",
]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@@ -1631,8 +1700,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"wasm-bindgen",
]
[[package]]
@@ -1819,6 +1890,31 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "hybrid-array"
version = "0.4.15"
@@ -1864,6 +1960,8 @@ dependencies = [
"num-traits",
"png",
"tiff",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -1882,6 +1980,15 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "itertools"
version = "0.13.0"
@@ -2101,7 +2208,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "matext4cgmath"
version = "0.1.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"cgmath",
"katexit",
@@ -2132,6 +2239,24 @@ dependencies = [
"autocfg",
]
[[package]]
name = "minisign"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aefd422a7a8b5efced01cd7cdf3771e62ebecbc90e3d27695002d3af6af94586"
dependencies = [
"ct-codecs",
"getrandom 0.4.3",
"rpassword",
"scrypt",
]
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2624,6 +2749,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -2682,6 +2813,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest 0.10.7",
"hmac",
]
[[package]]
name = "peniko"
version = "0.6.1"
@@ -3145,6 +3286,20 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "robust"
version = "1.2.0"
@@ -3160,6 +3315,27 @@ dependencies = [
"memchr",
]
[[package]]
name = "rpassword"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
dependencies = [
"libc",
"rtoolbox",
"windows-sys 0.61.2",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3207,12 +3383,95 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "salsa20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"
dependencies = [
"cipher",
]
[[package]]
name = "same-file"
version = "1.0.6"
@@ -3222,6 +3481,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
@@ -3234,6 +3502,40 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scrypt"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f"
dependencies = [
"pbkdf2",
"salsa20",
"sha2 0.10.9",
]
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.2",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "self_cell"
version = "1.3.0"
@@ -3489,8 +3791,8 @@ dependencies = [
[[package]]
name = "solidcraft-doc"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"log",
"serde",
@@ -3498,6 +3800,7 @@ dependencies = [
"sha2 0.10.9",
"solidcraft-geom",
"solidcraft-kernel",
"solidcraft-render",
"solidcraft-sketch",
"thiserror 2.0.21",
"web-time",
@@ -3505,8 +3808,8 @@ dependencies = [
[[package]]
name = "solidcraft-engine"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"log",
"serde",
@@ -3522,8 +3825,8 @@ dependencies = [
[[package]]
name = "solidcraft-geom"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -3531,8 +3834,8 @@ dependencies = [
[[package]]
name = "solidcraft-io"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"quick-xml",
"serde",
@@ -3547,13 +3850,15 @@ dependencies = [
[[package]]
name = "solidcraft-kernel"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"log",
"rayon",
"serde",
"serde_json",
"solidcraft-geom",
"spade",
"thiserror 2.0.21",
"truck-meshalgo",
"truck-modeling",
@@ -3564,8 +3869,8 @@ dependencies = [
[[package]]
name = "solidcraft-render"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"image",
"serde",
@@ -3574,8 +3879,8 @@ dependencies = [
[[package]]
name = "solidcraft-sketch"
version = "0.8.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
version = "0.11.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"serde",
"solidcraft-geom",
@@ -3619,6 +3924,12 @@ dependencies = [
"float-cmp",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "svgtypes"
version = "0.16.1"
@@ -3661,6 +3972,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -3907,7 +4228,7 @@ dependencies = [
[[package]]
name = "truck-meshalgo"
version = "0.4.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"array-macro",
"derive_more",
@@ -3957,7 +4278,7 @@ dependencies = [
[[package]]
name = "truck-shapeops"
version = "0.4.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"derive_more",
"itertools 0.13.0",
@@ -3972,7 +4293,7 @@ dependencies = [
[[package]]
name = "truck-stepio"
version = "0.3.0"
source = "git+https://github.com/bherbruck/solidcraft?rev=de1479029dd6821cffd28b70688a58e7f61f0cfd#de1479029dd6821cffd28b70688a58e7f61f0cfd"
source = "git+https://github.com/bherbruck/solidcraft?rev=a629236650c44ee73edf36fab0dcd2385103a610#a629236650c44ee73edf36fab0dcd2385103a610"
dependencies = [
"chrono",
"truck-geometry",
@@ -4053,6 +4374,40 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
dependencies = [
"base64 0.23.1",
"log",
"percent-encoding",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"ureq-proto",
"utf8-zero",
]
[[package]]
name = "ureq-proto"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
dependencies = [
"base64 0.23.1",
"http",
"httparse",
"log",
]
[[package]]
name = "usvg"
version = "0.48.1"
@@ -4072,6 +4427,12 @@ dependencies = [
"tiny-skia-path",
]
[[package]]
name = "utf8-zero"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
[[package]]
name = "uuid"
version = "1.28.0"
@@ -4372,6 +4733,15 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
@@ -4860,7 +5230,7 @@ dependencies = [
"calloop 0.13.0",
"cfg_aliases",
"concurrent-queue",
"core-foundation",
"core-foundation 0.9.4",
"core-graphics",
"cursor-icon",
"dpi",
@@ -4986,7 +5356,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.5.7"
version = "0.5.9"
dependencies = [
"serde_json",
]
@@ -5117,6 +5487,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zip"
version = "3.0.0"
+12 -11
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.5.7"
version = "0.5.9"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -27,6 +27,7 @@ fieldcraft-testkit = { path = "crates/testkit" }
fieldcraft-render = { path = "crates/render" }
fieldcraft-ui-egui = { path = "crates/ui-egui" }
fieldcraft-mcp = { path = "crates/mcp" }
fieldcraft-update = { path = "crates/update" }
# foundation
thiserror = "2"
@@ -58,13 +59,13 @@ rfd = "0.17"
# Geometry: SolidCraft's B-rep kernel (MIT OR Apache-2.0), pinned. Only crates/geometry uses it
# (plan/adr/0001-libraries.md).
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
solidcraft-geom = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-kernel = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-doc = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
solidcraft-io = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
# Runs SolidCraft command scripts (the test corpus recipes); only behind fieldcraft-geometry's
# `scripts` feature.
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
solidcraft-engine = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
[workspace.lints.rust]
unsafe_code = "forbid"
@@ -128,10 +129,10 @@ debug = "line-tables-only"
# reach a dependent workspace, so FieldCraft applies the same ones from the same pinned commit;
# keep this list and the rev in step with SolidCraft's [patch.crates-io].
[patch.crates-io]
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
truck-shapeops = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
truck-stepio = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
truck-meshalgo = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
matext4cgmath = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
# egui-wgpu with SolidCraft's fixes (vendor/egui-wgpu there): MSAA clamped to what the device
# supports and 1x on OpenGL adapters, so the requested 4x never fails pipeline validation at start.
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "de1479029dd6821cffd28b70688a58e7f61f0cfd" }
egui-wgpu = { git = "https://github.com/bherbruck/solidcraft", rev = "a629236650c44ee73edf36fab0dcd2385103a610" }
+30
View File
@@ -92,6 +92,25 @@ The same part also meshes all-hex automatically with the octree mesher (`mesh.he
![The FieldCraft window: a clamped cantilever with its supports, pressure, gravity and a coupled reference point drawn in the viewport](docs/media/setup-symbols.png)
## Examples
Ready-to-solve samples: open one from **File ▸ Samples** (or the start screen), or start the app
with `fieldcraft --sample NAME`, and press **Solve**. Each opens and solves within half a minute and is checked
against a closed form or a reference solution ([docs/examples.md](docs/examples.md)).
<table>
<tr>
<td width="33%" valign="top"><img src="docs/media/examples/drop-test.png" alt="Drop test" width="100%"><br><b>Drop test</b> (<code>drop-test</code>): an aluminium bracket dropped 2 m onto a tilted floor; explicit dynamics, the strike's stress waves</td>
<td width="33%" valign="top"><img src="docs/media/examples/rubber-seal.png" alt="Rubber seal" width="100%"><br><b>Rubber seal</b> (<code>rubber-seal</code>): a Mooney–Rivlin gasket ring squeezed 25 %; nonlinear static, large strain</td>
<td width="33%" valign="top"><img src="docs/media/examples/heated-bracket.png" alt="Heated bracket" width="100%"><br><b>Heated bracket</b> (<code>heated-bracket</code>): a clamped steel bracket heated at one end; steady heat and thermal stress</td>
</tr>
<tr>
<td width="33%" valign="top"><img src="docs/media/examples/bracket-hex.png" alt="Hex-meshed bracket" width="100%"><br><b>Hex-meshed bracket</b> (<code>bracket-hex</code>): the bracket split into 30 cells, meshed all-hex (hex20), von Mises</td>
<td width="33%" valign="top"><img src="docs/media/examples/crank-arm.png" alt="Bicycle crank arm" width="100%"><br><b>Bicycle crank arm</b> (<code>crank-arm</code>): an aluminium crank meshed structured all-hex (hex20) from a partitioned half and its mirror image, a rider's weight on the pedal; root bending within 0.3 % of M/Z</td>
<td width="33%" valign="top"><i>No picture yet: the viewport does not draw flow results (M12).</i><br><b>Flow past a bracket</b> (<code>flow-past</code>): air past an L-bracket on the floor; lattice Boltzmann flow, the drag and the force on each face</td>
</tr>
</table>
## Build
```sh
@@ -106,6 +125,7 @@ Rust 1.95 or later, with the `wasm32-unknown-unknown` target for `cargo xtask ci
## Documentation
- [Examples](docs/examples.md): the ready-to-solve samples and their checks
- [Architecture](docs/architecture.md): crates, layers and the meshing pipeline
- [Element library](docs/elements.md) and [verification and validation](docs/verification.md)
- [Capability checklist](docs/parity.md) and [roadmap](ROADMAP.md)
@@ -115,6 +135,16 @@ Rust 1.95 or later, with the `wasm32-unknown-unknown` target for `cargo xtask ci
- [Releasing](docs/releasing.md): how a release is built, verified and published
- [Contributing](CONTRIBUTING.md) and [agent instructions](AGENTS.md)
## Privacy
FieldCraft sends nothing until you agree. The first start asks once whether to share anonymous
usage (which tools you use, nothing from your models); Help › Settings… changes it, and
`FIELDCRAFT_TELEMETRY=0` turns it off. File names, paths, geometry, model contents, parameter
values and messages are never sent: [docs/privacy.md](docs/privacy.md) lists every event and
property. Crash reports and the log stay on your computer; Help › Report a Bug opens a GitHub issue
you review and submit yourself, with your session or model attached only if you tick them
([docs/crash-reports.md](docs/crash-reports.md)).
## License
Dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. Notices
+5 -5
View File
@@ -28,12 +28,12 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
|---|---|---|
| M0 Foundation | Workspace, quality gates, FE model, command engine with rollback and panic guard, CLI, geometry boundary on SolidCraft | done |
| M1 Geometry in and surface preparation | Open `.solidcraft` designs with persistent face names, assemblies placed (done); face-tagged 3MF (done); test corpus, `cargo xtask corpus` (done); exact predicates (done); quality metrics and certified validity gate (done); weld, closed/manifold/orientation and self-intersection checks, feature edges (`fieldcraft-mesh::surface`, `mesh.surface.check`, done) | in progress |
| M2 Tet meshing and size field | Size field (global, per face and edge seeds, curvature and proximity; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
| M2 Tet meshing and size field | Size field (global, curvature and proximity; edge seeds done: `mesh.seed.edge` on persistent design edge names (`<face>|<face>`) with a count or size, geometric bias and an exact, min or free constraint, shown as ticks and under Mesh › Seeds, honoured by the hex sweep, extrude, revolve, mapped, blocks and cells meshers through interval assignment (conflicting exact seeds named) and by the tet mesher, which divides the edge at the seed's nodes and grades its size field from them; per-face seeds to do; the `fieldcraft_mesh::size::SizeField` trait and edge-division helpers are in); Bowyer–Watson Delaunay (exact, symbolic perturbation, verified; `fieldcraft-mesh::delaunay`, done); robust CDT boundary recovery (Diazzi et al. 2023: implicit LNC Steiner points on segments, gift-wrapping facet recovery, inside/outside labelling, B-rep face tags on boundary tet faces, flip repair of rounding (§5.1) checked by the validity gate; `fieldcraft-mesh::cdt` and `mesh.tet.generate`, done: all 20 valid corpus parts); quality stage (done: `fieldcraft-mesh::tet` — curvature-graded size field, edge-collapse coarsening, constrained Delaunay refinement with boundary points on the B-rep faces and curves, ODT smoothing, Klingner–Shewchuk improvement, tet4 and tet10 with mid-side nodes on the B-rep, quality report; one validity criterion shared by the gate and both solvers; the filleted-bracket fillet stress converges, tests/oracle); mesh verify per set | in progress |
| M3 First deck | Sets and surfaces bound to SolidCraft face, edge, vertex and body names, resolved after meshing; materials (isotropic and orthotropic elastic, density) with a unit-system label and consistency check; sections (solid, shell, beam profiles) assigned by set; element formulation per region mapped to each solver; BCs (fixed, displacement, symmetry); loads (force and moment on reference points, pressure, gravity); reference points with kinematic and distributing coupling; steps (linear static, frequency) with explicit per-step load and BC tables and output presets; `model.check` naming every missing or bad item; `model.*` and `mesh.tag` commands (model definition: done); writers for Abaqus input (done: `deck.write`), Nastran SOL 101/103 (done: `deck.write`) and LS-DYNA implicit (done); the `.fieldcraft` file (text definition, binary mesh, geometry references reopened on load, journal; atomic saves, autosave and recovery; undo/redo on the journal: done) | in progress |
| M4 Own solver and first results | Element library per docs/elements.md (1D and 2D first); Linear static and modal solver (tet4/10, wedge6, hex8, hex20; sparse direct, Lanczos), verified against analytic solutions (solver: done — `fieldcraft-fem` kernels, `fieldcraft-solver` with nested dissection, sparse Cholesky and block Lanczos, `solve.static`/`solve.frequency`/`solve.probe`, patch, cantilever, Lamé, Kirsch and beam-frequency tests; reference points with kinematic and distributing couplings and moments by master–slave constraint elimination, verified by rigid motion, clamping, Saint-Venant tension, bending and tube torsion; 1D elements I: rod2/rod3 trusses, point masses, rotary inertia, springs and dashpots in both solvers and all three decks, verified by the method of joints, the three-bar truss, spring–mass, two-mass chain and torsional pendulum frequencies, and damped decay; 2D elements: plane stress, plane strain and axisymmetric tri3, tri6, quad4 (incompatible modes QM6), quad8 with two degrees of freedom per node, centrifugal loads, `mesh.planar` 2D meshes of polygons and planar faces, verified by patch tests, Kirsch, Lamé (plane strain and axisymmetric), rotating discs and cylinders, and a plane stress cantilever; deck mapping to Abaqus CPS/CPE/CAX, Nastran membranes, LS-DYNA ELFORM 12/13); shells and beams (done: quad4 MITC4 and tri3 MITC3 flat shells with a Hughes–Brezzi drilling rotation, two-node Timoshenko beams with profile properties and orientations, six degrees of freedom at shell and beam nodes shared with solids and trusses, section forces and surface stresses, verified by shell patch tests, Navier's plate, cantilever and portal-frame beams, and the Scordelis–Lo and pinched-cylinder benchmarks); results display (done: `results.*` commands, deformed shape to scale, banded contours of displacement, von Mises, principal and component stresses with a legend, mode shapes with their frequencies and animation, probing a node by clicking it, reaction force and moment sums per set, stale results marked after an edit; explicit steps: field frames by slider or animation with contours per frame, energy histories plotted) | started |
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); sweepable cells in a conforming mesh and tet–hex transition; automatic decomposition into sweepable and mappable regions, proposed as SolidCraft splits | started |
| M5 Structured hex | 2D quad meshing of faces (`fieldcraft-mesh::quad`: transfinite mapped meshes, free all-quad meshes of polygons with holes on prescribed boundary nodes, exact planar quad validity, shared `SizeField` and even edge divisions; done for planar faces); mapped hex of six-sided regions (trivariate TFI, curved faces) and sweep meshing (multi-level extrusions with imprinted cross-sections, revolutions, one-to-one sweeps through linking faces; interval assignment, hex8/hex20 on the geometry, B-rep face tags, `mesh.hex.generate`/`sweep`/`mapped`: done, 16 of 21 corpus parts all-hex); conforming interfaces between cells (done: `mesh.hex.blocks` meshes a part split with SolidCraft's Split Body into mapped blocks as one conforming mesh — composite faces for seams and tangent faces, interval assignment over all cells, shared faces meshed once, grading off holes and fillets, free-internal-face check; the filleted bracket in 30 cells, hex20 within 0.1 % of a fine tet10 tip deflection); partitions inside FieldCraft (done: datum planes and axes, `geometry.partition` cuts the open design by a datum plane, kept in the model and replayed when the design opens, the two faces of each cut paired by name); cells meshed each with its own method into one mesh (done: `mesh.cells` — hex where a method fits, else tet; matching interfaces merged node for node, others, such as hex next to tet, tied by dual mortar, verified by a tied hex–tet bar in tension to 1e-6); meshing half a symmetric part and mirroring it (done: `mesh.mirror` reflects hex8/hex20/tet4/tet10/wedge6 across a datum plane, right-handed, nodes on the plane merged, tags carried to the image half; a mirrored half bar equals the whole bar's mesh and bending deflection to 1e-12; samples `crank-arm` and `crank-mirror`: one datum, the half extruded in automatic blocks and mirrored, scaled Jacobian ≥ 0.37; or solving the half: `model.boundary_condition.symmetry` on a datum plane, a half bar with half the load bends as the whole to 1e-11); three-sided sweep regions mapped as triangle primitives (done: midpoint subdivision, dominance constraints in interval assignment); automatic blocks of extruded cross-sections (done: `hex::decompose` — holes separated, O-grids, cuts from concave corners and fillets chosen by block quality, kept only when no worse than the free mesh; nothing added to the model); pyramid transitions; automatic decomposition of 3D parts into sweepable and mappable regions | started |
| M6 Automatic hex | Octree/grid all-hex for any part (first version: done — `fieldcraft-mesh::octree`, `mesh.hex.octree`: 3-refinement grid with conforming templates refined by curvature, thickness and narrow faces, a core cleared to a manifold boundary, feature map onto it, padding and a pillow per patch capturing every sharp curve, foldover-free fitting, certified validity, B-rep face tags; the corpus hex column and the filleted-bracket oracle case; next: transitions for concave refined regions so thin and curved parts stop over-refining); hex-dominant by tet recombination; polycube for blocky parts; layers through thin walls; mesh editing and orphan-mesh import | started |
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (the model's contact definitions, `interaction.contact.*` with `find`, the deck mapping, `fieldcraft_fem::contact`'s closest-point projection and bucket grid, and the explicit solver's segmentation and friction return map are in place to reuse; the implicit solver refuses contact by name until then); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | planned |
| M7 Assemblies, contact and friction | Needs M15. Part instances from SolidCraft occurrences; tie between non-matching meshes (mortar: done — `interaction.tie`, dual mortar constraints in the implicit analyses, Abaqus `*TIE` and LS-DYNA tied contact, the tie patch test); implicit contact: surface-to-surface mortar and node-to-surface, penalty and augmented Lagrange, self-contact, automatic pair detection (mortar contact pairs with Coulomb friction in nonlinear static steps: done — segment-to-segment mortar with the consistent tangent by automatic differentiation of the segmentation, augmented Lagrangian with Uzawa updates to a gap tolerance, semismooth active set with a chattering cutback, small sliding without nonlinear geometry and finite sliding with it, overclosure adjusted or refused, Coulomb friction (stick/slip return map, static and kinetic coefficients, symmetrised tangent), pressure, gap, status, shear and slip output; verified by the contact patch test, Hertz cylinder and sphere, Newton's quadratic rate and sliding blocks; the linear analyses refuse contact by name); friction: Coulomb with stick–slip, static/kinetic, anisotropic, pressure-, rate- and temperature-dependent coefficients; contact output (pressure, slip, status); thermal contact conductance and frictional heating; wear (Archard); bolt pretension, connectors with behaviour (elastic, damped, stops, locks); amplitudes, multiple steps, restart; nonlinear steps in all three decks. Verified by Hertz (sphere and cylinder), the Cattaneo–Mindlin partial-slip problem, the sliding block, NAFEMS contact benchmarks | started |
| M8 Materials, explicit, shells, composites | Plasticity, hyperelasticity, damage data per solver; explicit dynamics decks (Abaqus/Explicit, LS-DYNA); midsurface shells; composite layups and material orientations, continuum shells on swept hex; hybrid (mixed u–p) hex8/hex20/tet10 for nearly incompressible materials (done); heat transfer (solids done: steady and θ-method transient conduction with flux, convection and sources, thermal strain in static steps (solids and 2D) and explicit dynamics (with plasticity), coupled temperature–displacement, `solve.heat`; deck output, 2D/shell/beam conduction planned) | started |
| M9 Post-processing and deck readers | Results readers for public formats (Nastran OP2, LS-DYNA d3plot, Abaqus `.fil`); XY and path plots, cuts, display groups, free-body forces; deck readers that keep unknown keywords; mesh convergence studies | planned |
| M10 Explicit dynamics | Shared element and material kernels with the implicit solver (`fem`); central-difference solver with lumped mass, stable time step, one-point hex8 with hourglass control and nodal-pressure tet4, bulk viscosity, energy accounting (X1 core: done — `fieldcraft-explicit`, `explicit_dynamic` steps with initial velocities, prescribed motion and planar rigid walls, `solve.explicit`/`solve.history`, small-strain linear elastic; bar wave, rigid-wall impact, energy balance and cantilever-period tests); large-deformation materials (X2: done — updated Lagrangian elements, Jaumann/Hughes–Winget and Green–Naghdi/Flanagan–Taylor rates, J2 bilinear/table plasticity, Johnson–Cook strength with heating and damage, erosion; materials gain `plastic`, `damage`, `erosion` with `model.material.plasticity`/`damage`; Dienes shear, rigid rotation, J2 uniaxial and Taylor-bar tests); contact (X3: done — `interaction.contact.pair`/`general`/`find`, segment-to-segment penalty contact both ways with polygon clipping (passes the contact patch test on non-matching meshes), pairs, general (all exterior faces) and self contact, bucket-grid search, deterministic on any thread count, a penalty from the masses and the stable increment that never shortens it, Coulomb friction with exponential decay by a return map, friction on rigid walls, contact energy and friction dissipation in the balance, initial penetrations adjusted or refused; Abaqus `*CONTACT PAIR`/`*CONTACT`/`*FRICTION` and LS-DYNA automatic contacts in the decks; verified by colliding bars, sliding blocks, the patch test and Hertz's sphere impact); hyperelastic materials (neo-Hookean, Mooney–Rivlin, Yeoh) on the shared material point with average nodal pressure tets, and opt-in mass scaling with the added mass reported: done; runs on hex and tet meshes | started |
@@ -52,7 +52,7 @@ pressure) is a degree of freedom of the existing DOF framework, not a separate s
| M23 Wave propagation and ultrasound | Elastic, acoustic and coupled waves from the explicit solver's 1D bar today to guided and ultrasonic waves, by two methods. Finite differences first, for fast 2D (then 3D) ultrasound on regular grids: staggered-grid velocity–stress FDTD (Virieux) and the elastodynamic finite integration technique for solids, the rotated staggered grid for anisotropic media, a k-space pseudospectral scheme for weakly heterogeneous tissue and water, all on grids voxelised from the face-tagged geometry by the LBM's exact voxeliser, with heterogeneous, layered and fluid–solid media, CPML boundaries, threads and the GPU backend; staircased curved boundaries scatter spuriously, so the FD grid is checked against the finite elements on curved parts. Finite elements for curved geometry and coupling with structures: spectral elements (high-order Gauss–Lobatto–Legendre hexes with diagonal mass) on the hex meshes, and a mesh check in elements per wavelength with the dispersion error it implies; absorbing boundaries (convolutional PML, absorbing layers with increasing damping) and infinite media; tone-burst sources (Hann-windowed cycles), point, line and surface excitation, and piezoelectric transducers (M19); anisotropic media (composites, crystals) and viscoelastic, power-law-in-frequency attenuation; fluid–solid interfaces and fluid-loaded plates; ultrasound in water and tissue, nonlinear acoustics (Westervelt, KZK) for focused ultrasound. Guided waves: dispersion curves by semi-analytical finite elements (SAFE) for plates, pipes, rails and layered and anisotropic laminates — Lamb, Rayleigh, Love and SH modes — with phase and group velocities and mode shapes; mode-selective excitation. Output: A-scans and B-scans at sensors, wavefield snapshots, 2D FFT (frequency–wavenumber) for mode identification, and time–frequency diagrams of any signal — short-time Fourier spectrograms, continuous wavelet transforms (Morlet), reassigned spectrograms and smoothed pseudo Wigner–Ville — with the SAFE or Rayleigh–Lamb group-velocity curves overlaid as arrival times, and group velocities extracted from the ridges. GPU paths (M12's backend) for long runs. Verified by Lamb's problem (point load on a half-space), Rayleigh-wave speed, Rayleigh–Lamb dispersion, Love waves in a layer over a half-space, reflection and transmission at interfaces, and published guided-wave measurements | planned |
| Continuous: verification and validation | Every capability checked against theory (closed forms), experiments (published measurements) and published benchmarks (NAFEMS, vendor benchmark and verification manuals such as Abaqus's), each case our own model in `tests/oracle/` with its cited reference and tolerance; `cargo xtask oracle` runs them and writes docs/oracle.md; once a case matches, our result is frozen as a fixture so fidelity cannot regress (docs/verification.md). Runner, fixtures and CI job: done; 26 theory cases (patch tests of every solid element, cantilevers, Lamé in 3D, plane strain and axisymmetric, Kirsch in 3D and plane stress, rotating disc and cylinder, beam frequencies, couplings, explicit waves, impact and J2 plasticity, CDT invariants), 9 published benchmarks (MacNeal–Harder solid tests, Scordelis–Lo with solids, NAFEMS LE1 in 3D and 2D, LE10, FV32) and 9 pending cases with citations (shells, thermal, static plasticity, Taylor bar, CFD); `mesh.block` mapped blocks and 2D patches build their meshes | started |
| Continuous: performance | CPU first, deterministic: results never depend on the thread count (fixed partitions, sums in a fixed order; checked by hashing results on 1, 2 and 7 threads). Supernodal left-looking Cholesky (11–15× faster than the column solver on one thread), parallel element matrices, stresses and Lanczos products, explicit element updates and LBM cell blocks on rayon threads (done — `fieldcraft-parallel`, `threads` on the solve commands, `FIELDCRAFT_THREADS`); parallel forward/back substitution and explicit tet4 assembly; GPU paths later, within a stated tolerance of the CPU | started |
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve: done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done), command schema as the public API | started |
| Continuous: desktop and agents | Desktop app (viewport, model tree, commands, control channel, the open design drawn, `ui.capture` of the whole window offscreen: done; toolbar of every capability from the catalogue, ready or coming soon with its milestone, icons drawn with VectorCraft, docs/features.md: done; the Craft-family shell — title bar, workspaces and ribbon drop-downs, browser, context panel, command search, journal timeline, light and dark themes — native file pickers with background opening, drag and drop and recent files, samples and one-click Solve, and an examples gallery of ready-to-solve samples, each checked by a test (docs/examples.md): done; MCP server over stdio, headless or bridged to the app, with read and write roots, docs/mcp.md: done; caps labels in Inter SemiBold; the README's analysis video recorded through MCP by `tools/demo-video`: done; support, load, reference-point and coupling symbols in the viewport and headless renders, with their browser toggles: done; symbols as wireframes, one mark per constrained degree of freedom, a constant size on screen with a size setting, highlighted with their selected definition, concentrated loads drawn over the part: done; selection by picking in the viewport — geometry faces, edges, vertices and bodies, mesh nodes, element faces and elements, box selection, hover, a Target row in command forms, `ui.select`/`ui.selection` and MCP `select`: done; a camera parameter for screenshots, a ribbon that follows the command being run: in progress; the browser build — the same app in a web page with browser file pickers, downloads, drops and autosave to browser storage, deployed to GitHub Pages from each release, docs/web.md: done; in-app updates — a daily check of GitHub Releases, Help › Check for Updates and Reinstall, downloads verified against the release key's signature of SHA256SUMS.txt and swapped in after closing, `app.update.check`, `fieldcraft-cli update`, Reload to update in the browser, docs/updates.md: done), command schema as the public API | started |
## Next
@@ -77,7 +77,7 @@ What exists and what is missing, by area; each gap is in a milestone above.
| Area | Today | Missing |
|---|---|---|
| Solution procedures | Linear static, nonlinear static (solids with geometric and material nonlinearity: hyperelasticity, J2 plasticity), frequency (Lanczos), steady and transient heat, coupled temperature–displacement, explicit dynamics, LBM flow | Nonlinear shells and beams, arc-length, buckling (M15); implicit, harmonic, random and spectrum dynamics (M16) |
| Contact, friction, adhesion | Explicit deformable contact (pairs, general, self; segment to segment, penalty) with Coulomb friction and exponential decay; rigid walls with friction; couplings, springs, dashpots | Implicit contact, tie, anisotropic and pressure- or temperature-dependent friction, thermal contact, wear, eroding contact (M7, M10); cohesive adhesion and debonding (M20) |
| Contact, friction, adhesion | Explicit deformable contact (pairs, general, self; segment to segment, penalty) with Coulomb friction and exponential decay; rigid walls with friction; implicit mortar contact pairs (augmented Lagrangian, Coulomb friction) in nonlinear static steps; ties between non-matching meshes (dual mortar); couplings, springs, dashpots | Implicit self contact, anisotropic and pressure- or temperature-dependent friction, thermal contact, wear, eroding contact (M7, M10); cohesive adhesion and debonding (M20) |
| Materials | Isotropic and orthotropic elasticity, density, thermal, J2 plasticity (bilinear, table, Johnson–Cook), Johnson–Cook damage and erosion, compressible neo-Hookean, Mooney–Rivlin and Yeoh hyperelasticity, Newtonian fluids | Elastomers beyond Yeoh (Ogden, Arruda–Boyce and the rest), viscoelasticity, viscoplasticity and creep, anisotropic and pressure-dependent plasticity, non-Newtonian viscosity, a cited material library and calibration (M17) |
| Composites and anisotropy | Orthotropic constants | Orientations, layups, ply results, failure criteria, homogenisation (M18) |
| Coupled fields | Thermal–structural (one way and coupled) | Piezoelectric, poroelastic, electro-thermal, acoustics (M19) |
+1334 -44
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -12,4 +12,8 @@ workspace = true
fieldcraft-engine = { workspace = true }
fieldcraft-io = { workspace = true }
fieldcraft-mcp = { workspace = true }
fieldcraft-update = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies]
fieldcraft-update = { workspace = true, features = ["mock"] }
+80
View File
@@ -0,0 +1,80 @@
//! `fieldcraft-cli crashes`: the crash reports the desktop app wrote on this computer
//! (docs/crash-reports.md): list them, show one, replay one, delete them.
use std::path::Path;
use fieldcraft_engine::crash;
use serde_json::json;
pub const USAGE: &str = "usage: fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]";
pub fn run(args: &[String]) -> Result<(), String> {
let dir = crash::default_dir().ok_or("no crash folder on this system (set FIELDCRAFT_CRASH_DIR)")?;
let id = || args.get(1).map(String::as_str).ok_or_else(|| USAGE.to_string());
match args.first().map(String::as_str) {
None | Some("list") => {
let reports = crash::list(&dir);
if args.iter().any(|a| a == "--json") {
return print_json(&json!({ "dir": dir.to_string_lossy(), "reports": reports }));
}
println!("crash reports in {}", dir.display());
if reports.is_empty() {
println!(" (none)");
}
for r in reports {
let times = if r.count > 1 { format!(" ×{}", r.count) } else { String::new() };
let cmd = r.command.map(|c| format!(" in {c}")).unwrap_or_default();
let replay = if r.replayable { " [replayable]" } else { "" };
println!(" {} {}{times}{cmd} v{}{replay}\n {}", r.id, r.kind, r.version, r.message);
}
Ok(())
}
Some("show") => print_json(&crash::read(&dir, id()?)?),
Some("replay") => replay(&dir, id()?),
Some("dir") => {
println!("{}", dir.display());
Ok(())
}
Some("clear") => {
println!("deleted {} report(s)", crash::clear(&dir, args.get(1).map(String::as_str)));
Ok(())
}
_ => Err(USAGE.to_string()),
}
}
fn print_json(v: &serde_json::Value) -> Result<(), String> {
println!("{}", serde_json::to_string_pretty(v).map_err(|e| e.to_string())?);
Ok(())
}
/// Run a report's commands on its model and say whether the crash happens again. Files the
/// commands write go to a scratch folder, never over the user's files.
fn replay(dir: &Path, id: &str) -> Result<(), String> {
let report = crash::read(dir, id)?;
let scratch = std::env::temp_dir().join(format!("fieldcraft-replay-{}", std::process::id()));
std::fs::create_dir_all(&scratch).map_err(|e| format!("{}: {e}", scratch.display()))?;
if report["kind"] == "unclean_exit" {
println!("this crash ended the app without a report: if this process ends abruptly, it reproduced");
}
println!("replaying on {}", report["model_path"].as_str().unwrap_or("a new model"));
let r = crash::replay(&report, &scratch);
let _ = std::fs::remove_dir_all(&scratch);
let r = r?;
for (i, (cmd, outcome)) in r.steps.iter().enumerate() {
match outcome {
Ok(()) => println!(" {:>3}. {cmd}: ok", i + 1),
Err(e) => println!(" {:>3}. {cmd}: {e}", i + 1),
}
}
let said = |k: &str| report[k].as_str().unwrap_or_default().to_string();
if r.reproduced {
println!("reproduced: the same internal error ({}) at {}", said("message"), said("location"));
} else if let Some((l, m)) = r.panics.first() {
println!("an internal error happened, but not the reported one: {m} at {l}");
println!("(the report says: {} at {})", said("message"), said("location"));
} else {
println!("did not reproduce: no internal error (fixed, or it depends on something the replay does not have)");
}
Ok(())
}
+15
View File
@@ -2,10 +2,15 @@
//! fieldcraft-cli run <script.json>
//! fieldcraft-cli features
//! fieldcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR] [--automation-write-root DIR]
//! fieldcraft-cli crashes [list [--json] | show <id> | replay <id> | dir | clear [<id>]]
//! fieldcraft-cli update --check | --install
//! fieldcraft-cli --version
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
mod crashes;
mod update;
use std::path::Path;
use std::process::ExitCode;
@@ -28,6 +33,14 @@ usage:
--automation-read-root DIR files may be read only inside DIR
--automation-write-root DIR files may be written only inside DIR (with either root,
the access a root left out is not granted)
fieldcraft-cli crashes [list|show <id>|replay <id>|dir|clear [<id>]]
the crash reports the desktop app wrote on this
computer (docs/crash-reports.md): list them (--json),
show one, replay one (does the crash happen again?),
print their folder, delete them
fieldcraft-cli update --check is a newer FieldCraft published? (app.update.check; JSON)
fieldcraft-cli update --install download the latest release, verify its signature and
checksum, and install it over this copy (docs/updates.md)
fieldcraft-cli --version print the version
";
@@ -52,6 +65,8 @@ fn main() -> ExitCode {
Ok(())
}
Some("mcp") => mcp(args.get(1..).unwrap_or(&[])),
Some("crashes") => crashes::run(args.get(1..).unwrap_or(&[])),
Some("update") => update::run(args.get(1..).unwrap_or(&[])),
Some("run") => args.get(1).ok_or_else(|| format!("run needs a script\n\n{USAGE}")).and_then(|p| run(p)),
Some("-V" | "--version") => {
println!("fieldcraft-cli {}", env!("CARGO_PKG_VERSION"));
+56
View File
@@ -0,0 +1,56 @@
//! `fieldcraft-cli update --check | --install` (docs/updates.md): the same check as the app's
//! Help › Check for Updates (`app.update.check`), and installing the latest release over this
//! copy of the CLI's install, verified against the release key first. `FIELDCRAFT_UPDATE_HOST`
//! points both at a local test server.
use fieldcraft_engine::Session;
use fieldcraft_update::install::{self, Finish};
use fieldcraft_update::net::Client;
use fieldcraft_update::stage::{self, Options};
use serde_json::json;
pub const USAGE: &str = "usage: fieldcraft-cli update --check | --install";
pub fn run(args: &[String]) -> Result<(), String> {
match args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
["--check"] => check(),
["--install"] => install(),
_ => Err(USAGE.into()),
}
}
fn check() -> Result<(), String> {
fieldcraft_engine::enable_update_checks(true);
let report = Session::default().execute("app.update.check", &json!({})).map_err(|e| e.to_string())?;
println!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
Ok(())
}
fn install() -> Result<(), String> {
let client = Client::from_env();
let check = client.check().map_err(|e| e.to_string())?;
if !check.newer() {
println!("FieldCraft {} is up to date (the latest release is {}).", check.current, check.latest.version);
return Ok(());
}
let here = install::here();
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
eprintln!("Downloading FieldCraft {} for {}…", check.latest.version, here.describe());
let progress = |done: u64, total: u64| {
if total > 0 && done == total {
eprintln!("Downloaded {} MB; verifying…", total / (1024 * 1024));
}
};
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
let staged = stage::stage(&client, &check.latest, &here, &options).map_err(|e| e.to_string())?;
match install::plan(&staged, false).map_err(|e| e.to_string())? {
Finish::Swap(plan) => {
stage::apply(&plan).map_err(|e| e.to_string())?;
println!("Installed FieldCraft {} ({}). A running FieldCraft app uses it from its next start.", staged.version, here.describe());
}
Finish::Package { file, command } => {
println!("Downloaded and verified {}.\nInstall it with the system's package manager:\n {command}", file.display());
}
}
Ok(())
}
+75
View File
@@ -0,0 +1,75 @@
//! `fieldcraft-cli crashes` on a crash folder of its own (`FIELDCRAFT_CRASH_DIR`).
use std::path::{Path, PathBuf};
use std::process::Command;
use fieldcraft_engine::Session;
use serde_json::{Value, json};
const ID: &str = "20261014-101500-00000000deadbeef";
/// A replayable report: a model with two nodes and a replay that adds a third.
fn folder() -> PathBuf {
let d = std::env::temp_dir().join(format!("fieldcraft-cli-crashes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
let r = d.join(ID);
std::fs::create_dir_all(&r).unwrap();
let mut s = Session::default();
for l in 1..=2 {
s.execute("mesh.node.add", &json!({"label": l, "xyz": [l, 0, 0]})).unwrap();
}
std::fs::write(r.join("model.fieldcraft"), s.file_bytes(None).unwrap()).unwrap();
let replay = json!({"commands": [
{"command": "mesh.node.add", "params": {"label": 3, "xyz": [3, 0, 0]}},
{"command": "file.save", "params": {"path": d.join("overwritten.fieldcraft")}},
]});
std::fs::write(r.join("replay.json"), replay.to_string()).unwrap();
let report = json!({
"format": "fieldcraft-crash/1", "id": ID, "kind": "unclean_exit", "signature": "00000000deadbeef", "count": 2,
"first_seen": "2026-10-14T10:15:00Z", "message": "FieldCraft ended without a clean exit while running `mesh.node.add`",
"location": "unclean exit in mesh.node.add", "command": {"command": "mesh.node.add", "params": {}},
"app": {"version": "9.9.9"}, "backtrace": [],
});
std::fs::write(r.join("report.json"), report.to_string()).unwrap();
d
}
fn cli(dir: &Path, args: &[&str]) -> (String, bool) {
let out = Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_CRASH_DIR", dir).output().unwrap();
(format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)), out.status.success())
}
#[test]
fn crashes_list_show_replay_and_clear() {
let d = folder();
let (out, ok) = cli(&d, &["crashes"]);
assert!(ok, "{out}");
assert!(out.contains(ID) && out.contains("unclean_exit ×2 in mesh.node.add") && out.contains("[replayable]"), "{out}");
let (out, ok) = cli(&d, &["crashes", "list", "--json"]);
assert!(ok);
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(v["reports"][0]["id"], ID);
let (out, ok) = cli(&d, &["crashes", "show", ID]);
assert!(ok);
let v: Value = serde_json::from_str(&out).unwrap();
assert!(v["model_path"].as_str().unwrap().ends_with("model.fieldcraft"));
let (out, ok) = cli(&d, &["crashes", "replay", ID]);
assert!(ok, "{out}");
assert!(out.contains("1. mesh.node.add: ok"), "{out}");
// A command that writes a file is refused outside the scratch folder: the replay never
// writes over the user's files.
assert!(out.contains("2. file.save: ") && out.contains("outside the write root"), "{out}");
assert!(!d.join("overwritten.fieldcraft").exists());
assert!(out.contains("did not reproduce"), "{out}");
let (out, ok) = cli(&d, &["crashes", "show", "../etc"]);
assert!(!ok && out.contains("no crash report"), "{out}");
let (out, ok) = cli(&d, &["crashes", "dir"]);
assert!(ok && out.trim() == d.to_string_lossy(), "{out}");
let (out, ok) = cli(&d, &["crashes", "clear"]);
assert!(ok && out.contains("deleted 1 report(s)"), "{out}");
let (out, _) = cli(&d, &["crashes"]);
assert!(out.contains("(none)"), "{out}");
let (out, ok) = cli(&d, &["crashes", "nope"]);
assert!(!ok && out.contains("usage"), "{out}");
let _ = std::fs::remove_dir_all(&d);
}
+36
View File
@@ -0,0 +1,36 @@
//! `fieldcraft-cli update --check` against a local release server (FIELDCRAFT_UPDATE_HOST).
use std::process::Command;
use fieldcraft_update::mock::Server;
use serde_json::{Value, json};
fn cli(host: &str, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_fieldcraft-cli")).args(args).env("FIELDCRAFT_UPDATE_HOST", host).output().unwrap()
}
#[test]
fn update_check_reports_the_latest_release() {
let server = Server::start().unwrap();
server.release("latest", &json!({"tag_name": "v99.0.0", "html_url": "https://github.com/jyviko/fieldcraft/releases/tag/v99.0.0", "assets": []}));
let out = cli(&server.url(), &["update", "--check"]);
assert!(out.status.success(), "{out:?}");
let report: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(report["current"], env!("CARGO_PKG_VERSION"));
assert_eq!((report["latest"].as_str(), report["newer"].as_bool(), report["signed"].as_bool()), (Some("99.0.0"), Some(true), Some(false)));
// A test build is not a release package: it checks but would not install.
assert_eq!(report["asset"], Value::Null);
assert_eq!(server.requests(), 1);
// The same version: not newer, and --install has nothing to do.
server.release("latest", &json!({"tag_name": format!("v{}", env!("CARGO_PKG_VERSION")), "assets": []}));
let out = cli(&server.url(), &["update", "--check"]);
assert_eq!(serde_json::from_slice::<Value>(&out.stdout).unwrap()["newer"], false);
let out = cli(&server.url(), &["update", "--install"]);
assert!(out.status.success() && String::from_utf8_lossy(&out.stdout).contains("is up to date"), "{out:?}");
// Unreachable: an error, not a crash.
let out = cli("http://127.0.0.1:1", &["update", "--check"]);
assert!(!out.status.success() && String::from_utf8_lossy(&out.stderr).contains("could not reach"), "{out:?}");
assert!(!cli(&server.url(), &["update"]).status.success());
}
+1 -1
View File
@@ -29,6 +29,6 @@ rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "DomTokenList", "CssStyleDeclaration", "Event", "EventTarget", "BeforeUnloadEvent", "Storage", "Crypto", "Headers", "Request", "RequestInit", "RequestCache", "Response"] }
# Autosaves kept in the browser's local storage, which holds text.
base64 = "0.22"
+75
View File
@@ -0,0 +1,75 @@
//! A new deployment of the web app: every half hour the page's own address is fetched past the browser's cache, and when it loads another build
//! of the app than the one running (Trunk names each build's files by their content hash), the
//! status bar offers "Reload to update" (docs/updates.md). Reloading asks first when the model
//! has unsaved changes, as closing the page does.
use std::cell::Cell;
use std::rc::Rc;
use wasm_bindgen::JsCast as _;
/// How often the page looks for a new deployment (seconds).
pub const INTERVAL: f64 = 30.0 * 60.0;
/// Watches for a new deployment.
pub struct Watch {
/// The build this page runs.
running: Option<String>,
/// A fetch found another build.
found: Rc<Cell<bool>>,
/// App time of the last look.
pub looked_at: f64,
}
impl Watch {
pub fn start() -> Watch {
let html = web_sys::window().and_then(|w| w.document()).and_then(|d| d.document_element()).map(|e| e.outer_html()).unwrap_or_default();
let running = crate::build_in_page(&html).map(str::to_string);
if running.is_none() {
log::info!("deploy: no hashed build in the page (a development server?); not watching");
}
Watch { running, found: Rc::default(), looked_at: 0.0 }
}
/// Whether a newer deployment was found.
pub fn found(&self) -> bool {
self.found.get()
}
/// Fetch the page again and compare its build with the running one.
pub fn look(&self) {
let (Some(running), Some(window)) = (self.running.clone(), web_sys::window()) else { return };
if self.found.get() {
return;
}
let url = window.location().pathname().unwrap_or_else(|_| "./".into());
let init = web_sys::RequestInit::new();
init.set_cache(web_sys::RequestCache::NoStore);
let promise = window.fetch_with_str_and_init(&url, &init);
let found = self.found.clone();
wasm_bindgen_futures::spawn_local(async move {
let text = async {
let response: web_sys::Response = wasm_bindgen_futures::JsFuture::from(promise).await.ok()?.dyn_into().ok()?;
if !response.ok() {
return None;
}
wasm_bindgen_futures::JsFuture::from(response.text().ok()?).await.ok()?.as_string()
};
// Offline or refused: look again next time.
if let Some(html) = text.await
&& let Some(deployed) = crate::build_in_page(&html)
&& deployed != running
{
log::info!("deploy: {deployed} is deployed (running {running})");
found.set(true);
}
});
}
}
/// Reload the page (the new deployment loads).
pub fn reload() {
if let Some(w) = web_sys::window() {
let _ = w.location().reload();
}
}
+37 -1
View File
@@ -8,7 +8,8 @@
//! - files live in the page ([`fieldcraft_io::fs`] keeps them in memory): File › Open and drops
//! read the computer's files into it; Save, Save As and Write Deck hand the written file out as
//! a download;
//! - autosaves for recovery are kept in the browser's local storage ([`storage`]);
//! - autosaves for recovery and the preferences are kept in the browser's local storage
//! ([`storage`], [`usage`]), and anonymous usage (when agreed) goes out with `fetch`;
//! - no control channel (a page can't listen on a socket);
//! - background jobs (meshing, solving) run on the page's one thread once the window has shown
//! that they run.
@@ -17,9 +18,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(target_arch = "wasm32")]
mod deploy;
#[cfg(target_arch = "wasm32")]
mod storage;
#[cfg(target_arch = "wasm32")]
mod usage;
#[cfg(target_arch = "wasm32")]
mod web;
#[cfg(target_arch = "wasm32")]
@@ -42,6 +47,25 @@ fn sample_in_query(query: &str) -> Option<String> {
})
}
/// The build of the app a page loads: the content-hashed name Trunk gives its WebAssembly
/// (`fieldcraft-web-<hash>_bg.wasm`). A new deployment loads another one.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
fn build_in_page(html: &str) -> Option<&str> {
const HEAD: &str = "fieldcraft-web-";
const TAIL: &str = "_bg.wasm";
let mut rest = html;
while let Some(at) = rest.find(HEAD) {
let candidate = rest.get(at..)?;
let hash = candidate.get(HEAD.len()..)?;
let len = hash.bytes().take_while(u8::is_ascii_alphanumeric).count();
if len > 0 && hash.get(len..)?.starts_with(TAIL) {
return candidate.get(..HEAD.len() + len + TAIL.len());
}
rest = candidate.get(HEAD.len()..)?;
}
None
}
/// The name a file from the computer is kept under in the page: its last path part, without
/// characters a path would read as folders.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
@@ -64,6 +88,18 @@ mod tests {
assert_eq!(sample_in_query("?samples=x"), None);
}
#[test]
fn the_running_build_is_found_in_the_page() {
let page = r#"<link rel="modulepreload" href="/fieldcraft/fieldcraft-web-1a2b3c.js"><link rel="preload" href="/fieldcraft/fieldcraft-web-1a2b3c_bg.wasm" as="fetch">"#;
assert_eq!(build_in_page(page), Some("fieldcraft-web-1a2b3c_bg.wasm"));
let next = page.replace("1a2b3c", "9f8e7d");
assert_ne!(build_in_page(page), build_in_page(&next));
// A development page (no hash) and other text: nothing to compare.
assert_eq!(build_in_page(r#"<script src="fieldcraft-web.js"></script>"#), None);
assert_eq!(build_in_page("fieldcraft-web-"), None);
assert_eq!(build_in_page(""), None);
}
#[test]
fn file_names_stay_in_their_folder() {
assert_eq!(safe_name("beam.fieldcraft"), "beam.fieldcraft");
+86
View File
@@ -0,0 +1,86 @@
//! Anonymous usage in the browser (docs/privacy.md): the same events and the same consent as the
//! desktop app, the choice kept in the browser's local storage with the other preferences. Queued
//! events are posted with `fetch` every half minute and when the page is closed or left (`keepalive`, so
//! a closing page still sends them); a failed post is dropped silently.
//!
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`: a build without one asks nothing
//! and sends nothing.
use fieldcraft_engine::usage;
use fieldcraft_ui_egui::files::PrefsStore;
use fieldcraft_ui_egui::privacy::UsageHost;
use wasm_bindgen::JsCast as _;
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
/// Where the preferences are kept in local storage.
const PREFS_KEY: &str = "fieldcraft-prefs";
/// How often queued events are sent (seconds).
pub const INTERVAL: f64 = 30.0;
fn key() -> Option<&'static str> {
KEY.map(str::trim).filter(|k| !k.is_empty())
}
fn local_storage() -> Option<web_sys::Storage> {
web_sys::window()?.local_storage().ok().flatten()
}
/// The preferences in local storage (navigation, privacy).
pub fn prefs_store() -> PrefsStore {
PrefsStore {
load: Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten().map(String::into_bytes)),
save: Box::new(|bytes| {
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
local_storage().ok_or("browser storage is turned off")?.set_item(PREFS_KEY, text).map_err(crate::web::js_err)
}),
}
}
/// What the window needs to ask and record, when the build has a key.
pub fn host() -> Option<UsageHost> {
// The browser's clock for command durations (the plain wasm target has none).
usage::set_clock(js_sys::Date::now);
key().is_some().then(|| UsageHost {
platform: "web",
os: "web",
arch: "wasm32",
new_id: Box::new(|| web_sys::window()?.crypto().ok().map(|c| c.random_uuid())),
})
}
/// Post what is queued.
pub fn send() {
let (Some(key), Some(window)) = (key(), web_sys::window()) else { return };
let url = format!("{}/batch/", usage::DEFAULT_HOST);
while let Some(batch) = usage::take_batch() {
let init = web_sys::RequestInit::new();
init.set_method("POST");
init.set_body(&wasm_bindgen::JsValue::from_str(&batch.body(key)));
// The Fetch standard's `keepalive` (a closing page still sends it); web-sys has no setter.
let _ = js_sys::Reflect::set(&init, &"keepalive".into(), &true.into());
let headers = web_sys::Headers::new().ok();
if let Some(h) = &headers {
let _ = h.set("Content-Type", "application/json");
init.set_headers(h);
}
let promise = window.fetch_with_str_and_init(&url, &init);
wasm_bindgen_futures::spawn_local(async move {
// Offline or refused: the batch is dropped.
if let Err(e) = wasm_bindgen_futures::JsFuture::from(promise).await {
log::debug!("usage: not sent: {}", crate::web::js_err(e));
}
});
}
}
/// When the page is closed or left: the session's length, then send.
pub fn send_when_hidden(window: &web_sys::Window) {
let on_hide = wasm_bindgen::closure::Closure::<dyn FnMut()>::new(|| {
usage::closing();
send();
});
if let Err(e) = window.add_event_listener_with_callback("pagehide", on_hide.as_ref().unchecked_ref()) {
log::warn!("usage: {}", crate::web::js_err(e));
}
on_hide.forget();
}
+27 -1
View File
@@ -74,6 +74,7 @@ pub fn start() {
fieldcraft_io::recovery::set_clock(|| js_sys::Date::now().max(0.0) as u64);
let Some(window) = web_sys::window() else { return };
ask_before_unload(&window);
crate::usage::send_when_hidden(&window);
let Some(canvas) = element(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
@@ -86,6 +87,10 @@ pub fn start() {
Box::new(|cc| {
let inbox = Inbox::default();
let mut app = ModelApp::new(Session::default()).with_services(services(inbox.clone(), cc.egui_ctx.clone()));
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
if let Some(host) = crate::usage::host() {
app = app.with_usage(host);
}
if let Some(rs) = &cc.wgpu_render_state {
let info = rs.adapter.get_info();
log::info!("fieldcraft-web: graphics {:?} {}, MSAA {}x", info.backend, info.name, rs.msaa_samples);
@@ -102,7 +107,8 @@ pub fn start() {
if recoverable > 0 {
app.set_status(format!("{recoverable} autosaved model(s) can be recovered: File › Recover…"), false);
}
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false }))
let deploy = crate::deploy::Watch::start();
Ok(Box::new(Shell { app, inbox, store, autosaver, autosaved_at: 0.0, storage_error: false, sent_at: 0.0, deploy }))
}),
)
.await;
@@ -188,6 +194,10 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
pick_save: Some(Box::new(|name: &str, _: &[Filter]| Some(page_path(name)))),
// The recent list holds the page's files, which go with the page.
recent_path: None,
// Preferences are kept in the browser's local storage.
prefs: Some(crate::usage::prefs_store()),
// egui opens links itself in the browser.
open_url: None,
}
}
@@ -202,6 +212,10 @@ struct Shell {
autosaved_at: f64,
/// The last autosave did not fit in the browser's storage (said once until one fits).
storage_error: bool,
/// App time usage events were last sent.
sent_at: f64,
/// Looks for a new deployment of the app.
deploy: crate::deploy::Watch,
}
impl Shell {
@@ -267,7 +281,19 @@ impl eframe::App for Shell {
self.open_arrived();
self.app.logic(ctx);
self.autosave(ctx);
if self.app.now - self.sent_at >= crate::usage::INTERVAL {
self.sent_at = self.app.now;
crate::usage::send();
}
UNSAVED.with(|u| u.set(self.app.session.is_dirty() && !self.app.session.journal.is_empty()));
if self.app.now - self.deploy.looked_at >= crate::deploy::INTERVAL || self.app.now < self.deploy.looked_at {
self.deploy.looked_at = self.app.now;
self.deploy.look();
}
if self.deploy.found() && !self.app.reload_offered() {
self.app.offer_reload(Box::new(crate::deploy::reload));
}
ctx.request_repaint_after(std::time::Duration::from_secs_f64(crate::deploy::INTERVAL));
}
/// Dropped files are read here (browsers read them asynchronously) and arrive through the
+87 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "fieldcraft"
description = "FieldCraft desktop app"
description = "Finite element modeling: meshing, model setup, solver decks and a linear solver"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -13,12 +13,98 @@ workspace = true
fieldcraft-engine = { workspace = true }
fieldcraft-ui-egui = { workspace = true }
fieldcraft-io = { workspace = true }
fieldcraft-update = { workspace = true }
rfd = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11"] }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# Usage analytics (docs/privacy.md): an HTTPS POST with rustls on ring, checked against the
# operating system's certificates (no bundled root list), and a random install id.
ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "platform-verifier"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }
getrandom = "0.3"
[build-dependencies]
# The Windows executable's icon resource (build.rs).
embed-resource = "3.0.12"
# Linux .deb and .rpm packages (cargo-deb, cargo-generate-rpm), built by packaging/linux/package.sh
# from the release binaries it has already built and stripped; it sets the version and the file
# names. The file list matches the tar.gz's (package.sh's staged tree; the release workflow
# compares them).
# The binaries link only glibc and libgcc_s. Windowing (Wayland, X11, xkbcommon), the GPU (Vulkan
# or EGL) and the file dialogs (the XDG desktop portal) are opened at run time, so they are no ELF
# NEEDED entries and the tools cannot find them: they are listed here.
[package.metadata.deb]
name = "fieldcraft"
maintainer = "FieldCraft contributors <[email protected]>"
copyright = "FieldCraft contributors"
section = "science"
priority = "optional"
extended-description = """\
FieldCraft turns geometry into analysis-ready finite element models: volume \
meshes, materials, sections, boundary conditions, loads and steps. It writes \
Abaqus input, Nastran bulk data and LS-DYNA keyword decks, and solves linear \
static and modal problems with its own solver. Includes fieldcraft-cli, a \
headless command runner and MCP server."""
depends = "$auto, libxkbcommon0, libxkbcommon-x11-0, libwayland-client0, libx11-6, libx11-xcb1, libxcb1, libxcursor1, libxi6, libvulkan1 | libegl1"
recommends = "mesa-vulkan-drivers, libegl-mesa0, xdg-desktop-portal"
assets = [
["target/release/fieldcraft", "usr/bin/", "755"],
["target/release/fieldcraft-cli", "usr/bin/", "755"],
["../../packaging/linux/io.github.jyviko.fieldcraft.desktop", "usr/share/applications/", "644"],
["../../assets/app-icon/icon.iconset/icon_16x16.png", "usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/icon_32x32.png", "usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/[email protected]", "usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/icon_128x128.png", "usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/icon_256x256.png", "usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/icon_512x512.png", "usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../assets/app-icon/icon.iconset/[email protected]", "usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", "644"],
["../../README.md", "usr/share/doc/fieldcraft/", "644"],
["../../LICENSE-MIT", "usr/share/doc/fieldcraft/", "644"],
["../../LICENSE-APACHE", "usr/share/doc/fieldcraft/", "644"],
["../../NOTICE", "usr/share/doc/fieldcraft/", "644"],
["../../THIRD-PARTY-LICENSES.txt", "usr/share/doc/fieldcraft/", "644"],
]
[package.metadata.generate-rpm]
name = "fieldcraft"
license = "MIT OR Apache-2.0"
url = "https://github.com/jyviko/fieldcraft"
assets = [
{ source = "target/release/fieldcraft", dest = "/usr/bin/fieldcraft", mode = "755" },
{ source = "target/release/fieldcraft-cli", dest = "/usr/bin/fieldcraft-cli", mode = "755" },
{ source = "../../packaging/linux/io.github.jyviko.fieldcraft.desktop", dest = "/usr/share/applications/io.github.jyviko.fieldcraft.desktop", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/icon_16x16.png", dest = "/usr/share/icons/hicolor/16x16/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/icon_32x32.png", dest = "/usr/share/icons/hicolor/32x32/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/[email protected]", dest = "/usr/share/icons/hicolor/64x64/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/icon_128x128.png", dest = "/usr/share/icons/hicolor/128x128/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/icon_256x256.png", dest = "/usr/share/icons/hicolor/256x256/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/icon_512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../assets/app-icon/icon.iconset/[email protected]", dest = "/usr/share/icons/hicolor/1024x1024/apps/io.github.jyviko.fieldcraft.png", mode = "644" },
{ source = "../../README.md", dest = "/usr/share/doc/fieldcraft/README.md", mode = "644", doc = true },
{ source = "../../LICENSE-MIT", dest = "/usr/share/doc/fieldcraft/LICENSE-MIT", mode = "644", doc = true },
{ source = "../../LICENSE-APACHE", dest = "/usr/share/doc/fieldcraft/LICENSE-APACHE", mode = "644", doc = true },
{ source = "../../NOTICE", dest = "/usr/share/doc/fieldcraft/NOTICE", mode = "644", doc = true },
{ source = "../../THIRD-PARTY-LICENSES.txt", dest = "/usr/share/doc/fieldcraft/THIRD-PARTY-LICENSES.txt", mode = "644", doc = true },
]
# The binaries' ELF dependencies (glibc, libgcc_s) are found automatically; these are opened at run
# time. Soname provides rather than package names, so the same requirements resolve on Fedora/RHEL
# and openSUSE.
require-sh = false
[package.metadata.generate-rpm.requires]
"libxkbcommon.so.0()(64bit)" = "*"
"libxkbcommon-x11.so.0()(64bit)" = "*"
"libwayland-client.so.0()(64bit)" = "*"
"libX11.so.6()(64bit)" = "*"
"libX11-xcb.so.1()(64bit)" = "*"
"libxcb.so.1()(64bit)" = "*"
"libXcursor.so.1()(64bit)" = "*"
"libXi.so.6()(64bit)" = "*"
"(libvulkan.so.1()(64bit) or libEGL.so.1()(64bit))" = ""
[package.metadata.generate-rpm.recommends]
mesa-vulkan-drivers = "*"
xdg-desktop-portal = "*"
+95 -5
View File
@@ -12,12 +12,15 @@
#![forbid(unsafe_code)]
mod control_server;
mod update;
mod usage;
use fieldcraft_engine::Session;
use fieldcraft_engine::autosave::{self, Autosaver};
use fieldcraft_engine::{Session, crash, logfile};
use fieldcraft_ui_egui::{Filter, ModelApp, Services};
const USAGE: &str = "usage: fieldcraft [--sample [parts|cantilever|impact]] [--control PORT] [FILE…] (FILE: .fieldcraft, .solidcraft or .3mf)";
const USAGE: &str =
"usage: fieldcraft [--sample [NAME]] [--control PORT] [FILE…] (NAME: a sample, docs/examples.md; FILE: .fieldcraft, .solidcraft or .3mf)";
const DEPTH_BITS: u8 = 24;
/// The window draws its own caption buttons where the OS ones would sit apart from the app bar.
const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
@@ -46,6 +49,10 @@ struct App {
autosaver: Option<Autosaver>,
/// App time of the last autosave check.
autosaved_at: f64,
/// The first frame was drawn (the crash journal says the app is up).
running: bool,
/// Sends the anonymous usage events, when this run may (docs/privacy.md).
usage: Option<usage::Sender>,
}
impl App {
@@ -60,6 +67,10 @@ impl App {
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
if !self.running {
self.running = true;
crash::activity("running");
}
self.app.logic(ctx);
if self.app.now - self.autosaved_at >= AUTOSAVE_SECONDS {
self.autosaved_at = self.app.now;
@@ -75,6 +86,16 @@ impl eframe::App for App {
{
log::warn!("autosave: {e}");
}
self.app.usage_closing();
if let Some(u) = self.usage.take() {
u.finish();
}
// An update the user chose to install: swapped in now that the window has closed.
if let Some(staged) = self.app.take_staged_update() {
update::finish(&staged);
}
log::info!("FieldCraft closed");
crash::end_session();
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(raw);
@@ -94,9 +115,57 @@ fn services() -> Services {
})),
// Beside the recovery folder in the per-user data folder.
recent_path: fieldcraft_io::recovery::default_dir().and_then(|d| d.parent().map(|p| p.join("recent.json"))),
prefs: fieldcraft_io::recovery::default_dir()
.and_then(|d| d.parent().map(|p| fieldcraft_ui_egui::files::PrefsStore::file(p.join("prefs.json")))),
open_url: Some(Box::new(open_url)),
}
}
/// Open a web link in the default browser, with the system's own opener: `open` (macOS),
/// `xdg-open` (Linux and the BSDs), `explorer` (Windows). The link is one argument, never
/// passed through a shell. Only https links are opened.
fn open_url(url: &str) -> Result<(), String> {
if !url.starts_with("https://") {
return Err(format!("not a web link: {}", url.chars().take(80).collect::<String>()));
}
let opener = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
let mut child = std::process::Command::new(opener).arg(url).spawn().map_err(|e| format!("{opener}: {e}"))?;
// Reaped off the window thread; its exit status says nothing (`explorer` exits with 1 even
// when it opened the link).
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
/// Crash reports and the log file (docs/crash-reports.md): reports of earlier runs that crashed
/// come back, for the window to offer. Both live in the app's data folder (a temporary one in
/// runs driven by automation); `FIELDCRAFT_CRASH_DIR` moves the crash folder.
fn start_reporting() -> Vec<crash::Summary> {
// First the crash reports: an unclean exit's report takes the dead run's lines from the log.
let crashed = crash::default_dir().map(|dir| crash::install(dir, crash::Build::current())).unwrap_or_default();
match fieldcraft_io::recovery::data_dir().map(|d| logfile::install(&d.join("logs"), log::LevelFilter::Info)) {
Some(Ok(path)) => eprintln!("fieldcraft: log {}", path.display()),
Some(Err(e)) => eprintln!("fieldcraft: no log file: {e}"),
None => {}
}
let b = crash::Build::current();
log::info!(
"FieldCraft {} started ({}), crash reports in {}",
b.version,
b.version_line(),
crash::default_dir().map(|d| d.display().to_string()).unwrap_or_default()
);
crash::activity("startup");
crashed
}
/// Command-line options.
#[derive(Debug, Default, PartialEq)]
struct Args {
@@ -148,6 +217,12 @@ fn main() -> eframe::Result {
std::process::exit(2);
}
};
if args.control.is_some() {
// A run driven by automation keeps its autosaves (and recent files and preferences, which
// live beside them), its crash reports and its log in a temporary folder, never the user's.
fieldcraft_io::recovery::use_automation_dir();
}
let crashed = start_reporting();
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("FieldCraft")
@@ -170,12 +245,26 @@ fn main() -> eframe::Result {
"FieldCraft",
options,
Box::new(move |cc| {
let mut app = ModelApp::new(Session::default()).with_services(services());
let mut session = Session::default();
// The window's model: its commands go into the crash journal.
session.crash_journal = crash::enabled();
let mut app = ModelApp::new(session).with_services(services());
// Anonymous usage: asked once, recorded only when the user agreed (docs/privacy.md).
let usage = match usage::host(args.control.is_some()) {
Some(host) => {
app = app.with_usage(host);
usage::start()
}
None => None,
};
// Updates (docs/updates.md): checked at most daily when on, installed only on a click.
fieldcraft_engine::enable_update_checks(true);
app = app.with_updates(update::host(cc.egui_ctx.clone(), args.control.is_some()));
app.custom_titlebar = CUSTOM_TITLEBAR;
app.integrated_titlebar = cfg!(target_os = "macos");
if let Some(rs) = &cc.wgpu_render_state {
let info = rs.adapter.get_info();
eprintln!("fieldcraft: graphics {:?} {}, MSAA {}x (requested {MSAA}x)", info.backend, info.name, rs.msaa_samples);
log::info!("graphics {:?} {} ({}), MSAA {}x (requested {MSAA}x)", info.backend, info.name, info.driver, rs.msaa_samples);
app.set_wgpu(rs, DEPTH_BITS, rs.msaa_samples, &cc.egui_ctx);
}
if let Some(port) = args.control {
@@ -195,7 +284,8 @@ fn main() -> eframe::Result {
}
Autosaver::new(&dir).map_err(|e| log::warn!("autosave unavailable: {e}")).ok()
});
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0 }))
app.announce_crashes(&crashed);
Ok(Box::new(App { app, autosaver, autosaved_at: 0.0, running: false, usage }))
}),
)
}
+105
View File
@@ -0,0 +1,105 @@
//! The desktop app's side of updates (docs/updates.md): it runs the window's update jobs
//! ([`fieldcraft_ui_egui::updates`]) on background threads with [`fieldcraft_update`], and swaps
//! a staged release in after the window has closed ([`finish`]).
//!
//! Automatic checks are off in runs driven by automation (`--control`) and under CI, so test
//! and agent runs never reach GitHub on their own; `FIELDCRAFT_UPDATE_HOST` (a local test
//! server) turns them back on. Help › Check for Updates works in every run.
use std::cell::Cell;
use std::path::Path;
use std::sync::mpsc;
use fieldcraft_ui_egui::updates::{Event, Job, UpdateHost};
use fieldcraft_update::install::{self, Finish, Install};
use fieldcraft_update::net::{Client, Which};
use fieldcraft_update::stage::{self, Options};
use fieldcraft_update::{Release, Staged};
/// What the window needs for updates.
pub fn host(ctx: egui::Context, automation: bool) -> UpdateHost {
let here = install::here();
log::info!("updates: {}", here.describe());
stage::clean_stale(&here);
let env = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty());
let automatic = env(fieldcraft_update::HOST_ENV) || !(automation || env("CI"));
let (tx, events) = mpsc::channel::<Event>();
let unsupported = here.unsupported();
let start = move |job: Job| {
let (tx, ctx, here) = (tx.clone(), ctx.clone(), here.clone());
let spawned = std::thread::Builder::new().name("fieldcraft update".into()).spawn(move || {
let send = |e: Event| {
let _ = tx.send(e);
ctx.request_repaint();
};
let client = Client::from_env();
match job {
Job::Check { manual } => send(Event::Checked { manual, result: client.check().map_err(|e| e.to_string()) }),
Job::Stage(release) => send(Event::Staged(stage_release(&client, &release, &here, &send))),
Job::Reinstall => {
let staged = client
.release(&Which::Version(fieldcraft_update::current()))
.map_err(|e| e.to_string())
.and_then(|r| stage_release(&client, &r, &here, &send));
send(Event::Staged(staged));
}
}
});
if let Err(e) = spawned {
log::warn!("updates: no thread: {e}");
}
};
UpdateHost { unsupported, automatic, start: Box::new(start), events, now: Box::new(now), open_file: Box::new(open_file) }
}
/// Download, verify and stage `release`, reporting each whole percent.
fn stage_release(client: &Client, release: &Release, here: &Install, send: &dyn Fn(Event)) -> Result<Staged, String> {
let downloads = fieldcraft_io::recovery::data_dir().map(|d| d.join("updates")).unwrap_or_else(|| std::env::temp_dir().join("fieldcraft-updates"));
let last = Cell::new(u64::MAX);
let progress = |done: u64, total: u64| {
let step = done.saturating_mul(100).checked_div(total).unwrap_or(done / (1024 * 1024));
if last.replace(step) != step {
send(Event::Progress(done, total));
}
};
let options = Options { key: fieldcraft_update::PUBLIC_KEY, downloads: &downloads, arch: std::env::consts::ARCH, progress: &progress };
let staged = stage::stage(client, release, here, &options).map_err(|e| e.to_string());
match &staged {
Ok(s) => log::info!("updates: FieldCraft {} verified and staged at {}", s.version, s.payload.display()),
Err(e) => log::warn!("updates: FieldCraft {} not staged: {e}", release.version),
}
staged
}
/// Swap `staged` in and start it: the window has closed, its autosave is closed.
pub fn finish(staged: &Staged) {
match install::plan(staged, true) {
Ok(Finish::Swap(plan)) => match stage::apply(&plan) {
Ok(()) => log::info!("updates: FieldCraft {} installed ({})", staged.version, staged.install.describe()),
Err(e) => log::error!("updates: FieldCraft {} not installed, the previous version is kept: {e}", staged.version),
},
Ok(Finish::Package { .. }) => {}
Err(e) => log::error!("updates: {e}"),
}
}
/// Seconds since the Unix epoch.
fn now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Open a downloaded package with the system's handler for it (Linux: the software installer).
fn open_file(path: &Path) -> Result<(), String> {
let opener = if cfg!(target_os = "macos") {
"open"
} else if cfg!(windows) {
"explorer"
} else {
"xdg-open"
};
let mut child = std::process::Command::new(opener).arg(path).spawn().map_err(|e| format!("{opener}: {e}"))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
+116
View File
@@ -0,0 +1,116 @@
//! Sending the anonymous usage events (docs/privacy.md) to PostHog Cloud EU: a background
//! thread posts the queued events ([`fieldcraft_engine::usage`]) in batches every half minute and
//! when the window closes. A failed post (offline, a slow network) drops its batch silently;
//! nothing waits on it but the thread.
//!
//! The project key is a build setting, `FIELDCRAFT_POSTHOG_KEY`, which only the release workflow
//! sets: local, development and fork builds have none and send nothing.
use std::sync::mpsc;
use std::time::Duration;
use fieldcraft_engine::usage;
use fieldcraft_ui_egui::privacy::UsageHost;
/// The PostHog project key the release build was made with.
const KEY: Option<&str> = option_env!("FIELDCRAFT_POSTHOG_KEY");
/// How often queued events are sent.
const INTERVAL: Duration = Duration::from_secs(30);
/// The longest one post may take.
const TIMEOUT: Duration = Duration::from_secs(10);
/// How long closing the window waits for the last batch.
const LAST_WAIT: Duration = Duration::from_secs(2);
fn key() -> Option<&'static str> {
KEY.map(str::trim).filter(|k| !k.is_empty())
}
/// What the window needs to ask and record, when this run may share usage: the build has a key,
/// `FIELDCRAFT_TELEMETRY` is not `0`, and neither CI nor `--control` automation runs it (unless
/// `FIELDCRAFT_TELEMETRY=1`).
pub fn host(automation: bool) -> Option<UsageHost> {
let telemetry = std::env::var("FIELDCRAFT_TELEMETRY").ok();
let ci = std::env::var_os("CI").is_some_and(|v| !v.is_empty());
usage::allowed(key().is_some(), telemetry.as_deref(), automation, ci).then(|| UsageHost {
platform: "desktop",
os: std::env::consts::OS,
arch: std::env::consts::ARCH,
new_id: Box::new(new_id),
})
}
/// A random (version 4) UUID from the operating system's random source.
fn new_id() -> Option<String> {
let mut b = [0u8; 16];
getrandom::fill(&mut b).ok()?;
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
let hex: String = b.iter().map(|x| format!("{x:02x}")).collect();
Some(format!("{}-{}-{}-{}-{}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]))
}
/// The sending thread; [`Sender::finish`] sends what is left and stops it.
pub struct Sender {
stop: mpsc::Sender<()>,
finished: mpsc::Receiver<()>,
}
/// Start the sending thread (only when the build has a key). `FIELDCRAFT_TELEMETRY_HOST`
/// replaces PostHog's host, for checking the payload against a local listener.
pub fn start() -> Option<Sender> {
let key = key()?;
let host = std::env::var("FIELDCRAFT_TELEMETRY_HOST").ok().filter(|h| !h.trim().is_empty()).unwrap_or_else(|| usage::DEFAULT_HOST.into());
let url = format!("{}/batch/", host.trim_end_matches('/'));
// rustls's process-wide crypto (ring); another part of the app may have installed it first.
let _ = rustls::crypto::ring::default_provider().install_default();
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(TIMEOUT))
.tls_config(ureq::tls::TlsConfig::builder().root_certs(ureq::tls::RootCerts::PlatformVerifier).build())
.build()
.into();
let (stop, stopped) = mpsc::channel::<()>();
let (done, finished) = mpsc::channel::<()>();
let spawned = std::thread::Builder::new().name("fieldcraft usage".into()).spawn(move || {
loop {
let last = !matches!(stopped.recv_timeout(INTERVAL), Err(mpsc::RecvTimeoutError::Timeout));
while let Some(batch) = usage::take_batch() {
if let Err(e) = agent.post(&url).header("Content-Type", "application/json").send(batch.body(key)) {
// Offline or refused: this batch is dropped, the rest waits for the next try.
log::debug!("usage: {} event(s) not sent: {e}", batch.events.len());
break;
}
}
if last {
let _ = done.send(());
return;
}
}
});
match spawned {
Ok(_) => Some(Sender { stop, finished }),
Err(e) => {
log::warn!("usage: no sending thread: {e}");
None
}
}
}
impl Sender {
/// Send what is queued (waiting briefly) and stop.
pub fn finish(self) {
let _ = self.stop.send(());
let _ = self.finished.recv_timeout(LAST_WAIT);
}
}
#[cfg(test)]
mod tests {
#[test]
fn install_ids_are_random_version_4_uuids() {
let (a, b) = (super::new_id().unwrap(), super::new_id().unwrap());
assert_ne!(a, b);
assert_eq!(a.len(), 36);
assert_eq!(a.as_bytes()[14], b'4');
assert!(matches!(a.as_bytes()[19], b'8' | b'9' | b'a' | b'b'), "{a}");
}
}
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>diagnostics.bug_report</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M12 8.5 L12 8.5 C14.209 8.5 16 10.291 16 12.5 L16 15.5 C16 17.709 14.209 19.5 12 19.5 L12 19.5 C9.791 19.5 8 17.709 8 15.5 L8 12.5 C8 10.291 9.791 8.5 12 8.5 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.9 5.8 C9.9 4.64 10.84 3.7 12 3.7 C13.16 3.7 14.1 4.64 14.1 5.8 C14.1 6.96 13.16 7.9 12 7.9 C10.84 7.9 9.9 6.96 9.9 5.8 Z" fill="none" stroke="#dde2ea" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 10.5 L12 18" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 11.5 L4.8 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 14.5 L4.4 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8.3 17.4 L5 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 11.5 L19.2 9.8" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 14.5 L19.6 14.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M15.7 17.4 L19 19.4" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>geometry.datum.axis</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M7 17 L19 5" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M20 4 L15 5.2 M20 4 L18.8 9" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5.5 18.5 L2.5 21.5" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
<path d="M8.8 12 C8.8 10.233 10.233 8.8 12 8.8 C13.767 8.8 15.2 10.233 15.2 12 C15.2 13.767 13.767 15.2 12 15.2 C10.233 15.2 8.8 13.767 8.8 12 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.6 12 C10.6 11.227 11.227 10.6 12 10.6 C12.773 10.6 13.4 11.227 13.4 12 C13.4 12.773 12.773 13.4 12 13.4 C11.227 13.4 10.6 12.773 10.6 12 Z" fill="#f0b44a"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>geometry.datum.point</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M3 16 L9 10 L21 10 L15 16 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 3 L12 11 M8 7 L16 7" fill="none" stroke="#4f9ce8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M10.2 7 C10.2 6.006 11.006 5.2 12 5.2 C12.994 5.2 13.8 6.006 13.8 7 C13.8 7.994 12.994 8.8 12 8.8 C11.006 8.8 10.2 7.994 10.2 7 Z" fill="#f0b44a"/>
<path d="M12 12.5 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1.5 2"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 846 B

Binary file not shown.
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.hex.blocks</title>
<title>mesh.cells</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>

Before

Width:  |  Height:  |  Size: 1008 B

After

Width:  |  Height:  |  Size: 1003 B

File renamed without changes.
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.hex.mapped</title>
<title>mesh.hex.generate</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M12 3 L20 7 L20 16 L12 20 L4 16 L4 7 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M4 7 L12 11 L20 7 M12 11 L12 20" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>

Before

Width:  |  Height:  |  Size: 882 B

After

Width:  |  Height:  |  Size: 884 B

-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.hex.sweep</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M3 8 L12 8 L12 17 L3 17 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M7.5 8 L7.5 17 M3 12.5 L12 12.5" fill="none" stroke="#dde2ea" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M3 8 L8 4 L21 4 L21 13 L12 17 M12 8 L21 4" fill="none" stroke="#dde2ea" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 13 L20 10 M18.17 12.63 L20 10 L16.8 9.88" fill="none" stroke="#4f9ce8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 825 B

Binary file not shown.
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>mesh.size.seed</title>
<title>mesh.seed.edge</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M3 19 C7 5 17 5 21 19" fill="none" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M1.7 19 C1.7 18.282 2.282 17.7 3 17.7 C3.718 17.7 4.3 18.282 4.3 19 C4.3 19.718 3.718 20.3 3 20.3 C2.282 20.3 1.7 19.718 1.7 19 Z" fill="#4f9ce8"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1 @@
{"shapes": [{"rect": [8, 8.5, 8, 11], "radius": 4, "stroke": "line", "width": 1.6}, {"circle": [12, 5.8, 2.1], "stroke": "line", "width": 1.6}, {"line": [12, 10.5, 12, 18], "stroke": "accent", "width": 1.5}, {"line": [8, 11.5, 4.8, 9.8], "stroke": "line"}, {"line": [8, 14.5, 4.4, 14.5], "stroke": "line"}, {"line": [8.3, 17.4, 5, 19.4], "stroke": "line"}, {"line": [16, 11.5, 19.2, 9.8], "stroke": "line"}, {"line": [16, 14.5, 19.6, 14.5], "stroke": "line"}, {"line": [15.7, 17.4, 19, 19.4], "stroke": "line"}]}
@@ -0,0 +1 @@
{"shapes": [{"d": "M7 17 L19 5", "stroke": "accent", "width": 2}, {"d": "M20 4 L15 5.2 M20 4 L18.8 9", "stroke": "accent", "width": 2}, {"d": "M5.5 18.5 L2.5 21.5", "stroke": "line", "dash": [1.5, 2]}, {"circle": [12, 12, 3.2], "fill": "soft", "stroke": "line", "width": 1.25}, {"circle": [12, 12, 1.4], "fill": "warm", "stroke": null}]}
@@ -0,0 +1 @@
{"shapes": [{"d": "M3 16 L9 10 L21 10 L15 16 Z", "fill": "soft", "stroke": "line", "width": 1.25}, {"d": "M12 3 L12 11 M8 7 L16 7", "stroke": "accent", "width": 2}, {"circle": [12, 7, 1.8], "fill": "warm", "stroke": null}, {"d": "M12 12.5 L12 20", "stroke": "line", "dash": [1.5, 2]}]}
File renamed without changes.
-1
View File
@@ -1 +0,0 @@
{"shapes": [{"rect": [3, 8, 9, 9], "fill": "soft", "stroke": "line"}, {"d": "M7.5 8 L7.5 17 M3 12.5 L12 12.5", "stroke": "line", "width": 1}, {"d": "M3 8 L8 4 L21 4 L21 13 L12 17 M12 8 L21 4", "stroke": "line", "width": 1.25}, {"d": "M14 13 L20 10 M18.17 12.63 L20 10 L16.8 9.88", "stroke": "accent", "width": 1.5}]}
File renamed without changes.
+1
View File
@@ -0,0 +1 @@
{"shapes": [{"d": "M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z", "fill": "soft", "stroke": "line"}, {"circle": [12, 13, 2.6], "fill": "accent", "stroke": "accent", "width": 1}, {"d": "M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5", "stroke": "warm", "width": 1.5}]}
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24">
<title>view.show_all</title>
<g id="Layer_1" data-name="Layer 1">
<path d="M2.5 13 C5.5 7.5 18.5 7.5 21.5 13 C18.5 18.5 5.5 18.5 2.5 13 Z" fill="#2d4e70" stroke="#dde2ea" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.4 13 C9.4 11.564 10.564 10.4 12 10.4 C13.436 10.4 14.6 11.564 14.6 13 C14.6 14.436 13.436 15.6 12 15.6 C10.564 15.6 9.4 14.436 9.4 13 Z" fill="#4f9ce8" stroke="#4f9ce8" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 2.5 L12 5 M5.5 4.5 L7 6.5 M18.5 4.5 L17 6.5" fill="none" stroke="#f0b44a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 820 B

Binary file not shown.
+20
View File
@@ -28,6 +28,11 @@
//! initial overclosure have no Abaqus counterpart and are noted in comments (Abaqus chooses its
//! own penalty and resolves overclosure in the first increment).
//!
//! # Ties
//!
//! Each tie is `*TIE, NAME=…, ADJUST=NO` with the secondary surface first and its position
//! tolerance when it has one: FieldCraft ties the nodes where they are (no adjustment).
//!
//! # Steps and the activity table
//!
//! The model lists, for every step, exactly the boundary conditions and loads active in it; Abaqus
@@ -187,6 +192,7 @@ pub fn write_resolved(model: &Model, r: &Resolved) -> Result<String> {
d.discrete_properties(&discrete)?;
d.couplings(model, r);
d.contacts(model, r)?;
d.ties(model)?;
d.steps(model, r)?;
Ok(d.out)
}
@@ -1042,6 +1048,20 @@ impl Deck {
Ok(())
}
/// Ties: `*TIE` per tie, secondary surface first.
fn ties(&mut self, model: &Model) -> Result<()> {
if model.ties().is_empty() {
return Ok(());
}
self.comment("Ties: each secondary surface bonded to its main surface");
for (name, t) in model.ties() {
let tolerance = t.position_tolerance.map_or(String::new(), |v| format!(", POSITION TOLERANCE={v:?}"));
self.line(&format!("*TIE, NAME={name}, ADJUST=NO{tolerance}"));
self.line(&format!("{}, {}", t.secondary, t.main));
}
Ok(())
}
fn boundary_lines<'n>(&mut self, model: &Model, r: &Resolved, names: impl IntoIterator<Item = &'n String>) -> Result<()> {
for name in names {
let Some(bc) = model.boundary_condition(name) else { continue };
+20 -1
View File
@@ -23,7 +23,8 @@
//! node set), distributing as `*CONSTRAINED_INTERPOLATION` (the reference point dependent on
//! the set's translations, equal weights);
//! - contact: a pair as `*CONTACT_AUTOMATIC_SURFACE_TO_SURFACE` between segment sets (the
//! secondary surface first), general contact as `*CONTACT_AUTOMATIC_SINGLE_SURFACE` on a segment
//! secondary surface first; a tie as `*CONTACT_TIED_SURFACE_TO_SURFACE` likewise), general
//! contact as `*CONTACT_AUTOMATIC_SINGLE_SURFACE` on a segment
//! set or on every part (`surfatyp` 5); the static and kinetic coefficients and the decay
//! coefficient (`fs`, `fd`, `dc`: the same exponential decay law) and the penalty scale on both
//! sides (`sfsa`, `sfsb`, a factor on LS-DYNA's own default stiffness). LS-DYNA moves nodes
@@ -280,6 +281,9 @@ fn plan<'a>(model: &'a Model, r: &Resolved) -> Result<Plan<'a>> {
for c in model.contacts().values() {
segment_sets.extend(c.surfaces.sets());
}
for t in model.ties().values() {
segment_sets.extend([t.main.as_str(), t.secondary.as_str()]);
}
let mut gravity_sets: BTreeSet<Option<&str>> = BTreeSet::new();
for step in model.steps() {
if matches!(step.procedure, Procedure::ExplicitDynamic(_)) {
@@ -733,6 +737,21 @@ fn contacts(d: &mut Deck, model: &Model, plan: &Plan) -> Result<()> {
d.header(&["sfsa", "sfsb"]);
d.card([Field::from(c.penalty_scale), Field::from(c.penalty_scale)]);
}
// Ties: a tied surface-to-surface contact between the segment sets, secondary first.
for (name, t) in model.ties() {
let sid = |set: &str| plan.sets.get(set).copied().ok_or_else(|| broken(format!("tie `{name}`: set `{set}`")));
d.comment(&format!("tie `{name}`"));
if t.position_tolerance.is_some() {
d.comment("FieldCraft's position tolerance: LS-DYNA ties the nodes within its own search distance");
}
d.line("*CONTACT_TIED_SURFACE_TO_SURFACE");
d.header(&["surfa", "surfb", "surfatyp", "surfbtyp"]);
d.card([Field::from(sid(&t.secondary)?), Field::from(sid(&t.main)?), Field::from(0), Field::from(0)]);
d.header(&["fs", "fd", "dc"]);
d.card([Field::from(0.0), Field::from(0.0), Field::from(0.0)]);
d.header(&["sfsa", "sfsb"]);
d.card([Field::from(1.0), Field::from(1.0)]);
}
Ok(())
}
+3
View File
@@ -337,6 +337,9 @@ impl<'m> Deck<'m> {
for name in self.model.contacts().keys() {
self.problems.insert(format!("contact `{name}` (Nastran's linear solutions SOL 101 and 103 have no contact)"));
}
for name in self.model.ties().keys() {
self.problems.insert(format!("tie `{name}` (this writer does not write glued contact yet)"));
}
for sub in &mut self.subcases {
if matches!(sub.step.procedure, Procedure::Frequency { .. }) {
sub.method = Some(next_id(&mut self.next_sid)?);
+5 -1
View File
@@ -4,7 +4,7 @@
use fieldcraft_decks::{Error, abaqus, lsdyna, nastran};
use fieldcraft_model::{
BoundaryCondition, Contact, ContactSurfaces, Elastic, ElementFace, ElementKind, Friction, InitialPenetration, Material, Model, Procedure,
Section, SectionKind, Set, Step, Target, UnitSystem,
Section, SectionKind, Set, Step, Target, Tie, UnitSystem,
};
/// Two unit hex8 cubes, the second on top of the first (separate nodes), with face sets for the
@@ -42,6 +42,7 @@ fn model() -> Model {
m.add_contact("stack", pair).unwrap();
m.add_contact("everything", Contact { friction: Friction::coulomb(0.1), ..Contact::new(ContactSurfaces::General { surface: None }) }).unwrap();
m.add_contact("fold", Contact { penalty_scale: 0.5, ..Contact::new(ContactSurfaces::General { surface: Some("upper".into()) }) }).unwrap();
m.add_tie("glue", Tie { position_tolerance: Some(0.05), ..Tie::new("lower", "upper") }).unwrap();
m
}
@@ -56,6 +57,7 @@ fn abaqus_writes_interactions_pairs_and_general_contact() {
"*SURFACE INTERACTION, NAME=fold-interaction\n*FRICTION\n0.0\n",
"*CONTACT\n*CONTACT INCLUSIONS, ALL EXTERIOR\n*CONTACT INCLUSIONS\nupper,\n*CONTACT PROPERTY ASSIGNMENT\n, , everything-interaction\nupper, upper, fold-interaction\n",
"** contact `fold`: penalty scale 0.5",
"*TIE, NAME=glue, ADJUST=NO, POSITION TOLERANCE=0.05\nupper, lower\n",
] {
assert!(deck.contains(expected), "{expected}\n{deck}");
}
@@ -83,6 +85,7 @@ fn lsdyna_writes_automatic_contacts_on_segment_sets() {
for set in ["lower", "upper"] {
assert!(deck.contains(&format!("*SET_SEGMENT_TITLE\n{set}\n")), "{set}\n{deck}");
}
assert_eq!(after("*CONTACT_TIED_SURFACE_TO_SURFACE"), ["4 3 0 0", "0.0 0.0 0.0", "1.0 1.0"], "{deck}");
}
#[test]
@@ -92,6 +95,7 @@ fn nastran_refuses_contact_by_name() {
for name in ["everything", "fold", "stack"] {
assert!(what.contains(&format!("contact `{name}`")), "{what}");
}
assert!(what.contains("tie `glue`"), "{what}");
}
other => panic!("{other:?}"),
}
+5 -3
View File
@@ -10,7 +10,8 @@ workspace = true
[dependencies]
fieldcraft-model = { workspace = true }
fieldcraft-geometry = { workspace = true }
# Samples build their geometry from SolidCraft scripts (sample.rs).
fieldcraft-geometry = { workspace = true, features = ["scripts"] }
fieldcraft-mesh = { workspace = true }
fieldcraft-io = { workspace = true }
fieldcraft-decks = { workspace = true }
@@ -24,8 +25,9 @@ serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# app.update.check (docs/updates.md); the browser build has no update check.
fieldcraft-update = { workspace = true }
[dev-dependencies]
png = { workspace = true }
zip = { workspace = true }
# Multi-body designs from SolidCraft scripts in tests.
fieldcraft-geometry = { workspace = true, features = ["scripts"] }
+27
View File
@@ -0,0 +1,27 @@
{"commands": [
{"command": "parameters.change", "params": {"name": "arm_thickness", "expression": "16 mm"}},
{"command": "sketch.create", "params": {"plane": "XY", "name": "ArmProfile"}},
{"command": "sketch.line", "params": {"points": [[15.471735240951828, -18.362928548901984], [160.67227699330076, -12.384082712040556]], "ids": ["lo"]}},
{"command": "sketch.arc.center_point", "params": {"center": [160.91912663845798, -18.3790026658586], "start": [161.58293237729853, -12.415835559271503], "end": [160.67227699330076, -12.384082712040556]}},
{"command": "sketch.arc.center_point", "params": {"center": [170.0, 0], "start": [161.58293237729853, -12.415835559271503], "end": [161.58293237729853, 12.415835559271503]}},
{"command": "sketch.arc.center_point", "params": {"center": [160.91912663845798, 18.3790026658586], "start": [160.67227699330076, 12.384082712040556], "end": [161.58293237729853, 12.415835559271503]}},
{"command": "sketch.line", "params": {"points": [[160.67227699330076, 12.384082712040556], [15.471735240951828, 18.362928548901984]], "ids": ["hi"]}},
{"command": "sketch.arc.center_point", "params": {"center": [15.883151316213851, 28.354461805265395], "start": [13.455063072993756, 18.65372021077189], "end": [15.471735240951828, 18.362928548901984]}},
{"command": "sketch.arc.center_point", "params": {"center": [0, 0], "start": [13.455063072993756, 18.65372021077189], "end": [13.455063072993756, -18.65372021077189]}},
{"command": "sketch.arc.center_point", "params": {"center": [15.883151316213851, -28.354461805265395], "start": [15.471735240951828, -18.362928548901984], "end": [13.455063072993756, -18.65372021077189]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"distance": "arm_thickness", "body_name": "CrankArm", "name": "Arm"}},
{"command": "solid.cylinder", "params": {"diameter": 46.0, "height": 22, "base": [0, 0, 0], "operation": "join", "targets": ["CrankArm"], "name": "SpindleBoss"}},
{"command": "solid.cylinder", "params": {"diameter": 30.0, "height": 20, "base": [170.0, 0, 0], "operation": "join", "targets": ["CrankArm"], "name": "PedalBoss"}},
{"command": "sketch.create", "params": {"plane": "XY", "name": "BackPocket"}},
{"command": "sketch.rectangle.two_point", "params": {"p0": [48, -7], "p1": [130, 7]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"distance": 8, "operation": "cut", "targets": ["CrankArm"], "name": "Pocket"}},
{"command": "sketch.create", "params": {"plane": "XY", "name": "SpindleSquare"}},
{"command": "sketch.rectangle.center", "params": {"center": [0, 0], "corner": [6.35, 6.35]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"through_all": true, "operation": "cut", "targets": ["CrankArm"], "name": "SpindleTaper"}},
{"command": "solid.fillet", "params": {"edges": [[6.35, 6.35, 10], [-6.35, 6.35, 10], [-6.35, -6.35, 10], [6.35, -6.35, 10]], "radius": 1.5, "name": "SquareCornerFillet"}},
{"command": "solid.hole", "params": {"position": [170.0, 0, 20], "diameter": 14, "name": "PedalHole"}},
{"command": "solid.fillet", "params": {"edges": [[48, -7, 4], [48, 7, 4], [130, -7, 4], [130, 7, 4]], "radius": 5, "name": "PocketCornerFillet"}}
]}
+2
View File
@@ -47,6 +47,7 @@ impl Autosaver {
let bytes = s.file_bytes(None)?;
self.slot.write(&bytes, s.path.as_deref(), s.model.nodes().len(), s.model.elements().len())?;
self.saved = Some(s.revision());
crate::crash::autosaved(s, &self.slot.file());
Ok(true)
}
@@ -84,6 +85,7 @@ mod tests {
let listed = s.execute("file.recovery.list", &json!({"dir": dir})).unwrap();
assert_eq!(listed[0]["id"], id);
assert_eq!(listed[0]["nodes"], 1);
assert!(listed[0]["age"].as_u64().is_some_and(|a| a < 60), "{listed}");
let mut next = Session::default();
let r = next.execute("file.recover", &json!({"id": id, "dir": dir})).unwrap();
assert_eq!(r["nodes"], 1);
+393
View File
@@ -0,0 +1,393 @@
//! Bug report drafts (Help › Report a Bug, and Report it after a crash): a GitHub new-issue link
//! that fills in the bug form (`.github/ISSUE_TEMPLATE/bug.yml`), and the files to attach.
//!
//! Nothing here sends anything. The user reviews the draft, then their browser opens the issue
//! form, which they submit or not.
//!
//! What a draft holds by default: the version, the OS, what went wrong (the user's words, the
//! last error or the crash's message) and, for a crash, where it happened. The user's home
//! folder is shown as `~`. Only with **Share my session** does it also carry the commands that
//! built the model (the replayable journal, which can name the user's files), and only with
//! **Include the model** as well the model file. A session too long for the link (GitHub
//! refuses long new-issue links) goes out as a file to attach and on the clipboard instead; the
//! model file is always one to attach.
use serde_json::{Value, json};
use crate::crash::without_home;
/// The issue form.
pub const ISSUE_URL: &str = "https://github.com/jyviko/fieldcraft/issues/new";
/// The longest link a draft opens: GitHub refuses new-issue links much past 8 KB.
pub const MAX_URL: usize = 7000;
/// The session file a draft attaches.
pub const SESSION_FILE: &str = "fieldcraft-session.json";
/// The model file a draft attaches.
pub const MODEL_FILE: &str = "model.fieldcraft";
/// Backtrace frames a crash's draft quotes.
const FRAMES: usize = 12;
/// A field's text is cut at this many bytes.
const MAX_FIELD: usize = 3000;
/// What to put in a draft.
#[derive(Clone, Debug, Default)]
pub struct Input {
pub title: String,
/// What happened: the user's words, or the last error.
pub observed: String,
/// A crash report (`crash::read`), when reporting one.
pub crash: Option<Value>,
/// Attach the replayable commands.
pub share_session: bool,
/// The commands (each `{command, params}`) that rebuild the model from `model` (or from an
/// empty model when there is none).
pub commands: Vec<Value>,
/// Attach the model file too (only with `share_session`).
pub include_model: bool,
pub model: Option<Vec<u8>>,
}
/// A file the user attaches to the issue.
#[derive(Clone, Debug, PartialEq)]
pub struct Attachment {
pub name: String,
pub bytes: Vec<u8>,
/// What it is, for the review.
pub what: String,
}
/// A draft ready for review.
#[derive(Clone, Debug, PartialEq)]
pub struct Draft {
pub title: String,
/// The bug form's fields by id (`observed`, `reproduction`, `evidence`, `version`), as the
/// link fills them.
pub fields: Vec<(&'static str, String)>,
/// The link that opens the filled form.
pub url: String,
/// Files to attach (the session when too long for the link, the model).
pub attachments: Vec<Attachment>,
/// Text to put on the clipboard (the session, when it is an attachment).
pub clipboard: Option<String>,
}
impl Draft {
/// The draft as JSON (attachments by name, size and what they are).
pub fn to_json(&self) -> Value {
json!({
"title": self.title,
"fields": self.fields.iter().map(|(k, v)| (k.to_string(), json!(v))).collect::<serde_json::Map<String, Value>>(),
"url": self.url,
"attachments": self.attachments.iter().map(|a| json!({"name": a.name, "bytes": a.bytes.len(), "what": a.what})).collect::<Vec<_>>(),
"clipboard": self.clipboard.as_ref().map(String::len),
})
}
}
/// `v0.5.8 (abc1234), macos aarch64`.
pub fn version_line(version: &str, commit: &str) -> String {
let commit = if commit.is_empty() { String::new() } else { format!(" ({commit})") };
format!("v{version}{commit}, {} {}", std::env::consts::OS, std::env::consts::ARCH)
}
/// Percent-encode `s` for a query value (RFC 3986 unreserved characters stay).
pub fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
fn cut(s: &str, n: usize) -> String {
if s.len() <= n {
return s.to_string();
}
let mut end = n;
while !s.is_char_boundary(end) {
end -= 1;
}
format!("{}\n[cut: {} bytes in all]", s.get(..end).unwrap_or_default(), s.len())
}
fn link(title: &str, fields: &[(&'static str, String)]) -> String {
let mut url = format!("{ISSUE_URL}?template=bug.yml&title={}", encode(title));
for (k, v) in fields {
if !v.is_empty() {
url.push_str(&format!("&{k}={}", encode(v)));
}
}
url
}
/// What a crash report says, for the evidence field: its kind, message, place, command (its id;
/// its parameters only with the session) and the top of its backtrace.
fn crash_evidence(report: &Value, share: bool) -> String {
let s = |k: &str| report.get(k).and_then(Value::as_str).unwrap_or("?");
let mut out =
format!("Crash report `{}` ({}), seen {} time(s)\n\n", s("id"), s("kind"), report.get("count").and_then(Value::as_u64).unwrap_or(1));
out.push_str(&format!("Message: {}\nAt: {}\n", without_home(s("message")), without_home(s("location"))));
if let Some(c) = report.get("command").filter(|c| !c.is_null()) {
let id = c.get("command").and_then(Value::as_str).unwrap_or("?");
match c.get("params").filter(|_| share) {
Some(p) => out.push_str(&format!("Command: `{id}` {}\n", without_home(&p.to_string()))),
None => out.push_str(&format!("Command: `{id}`\n")),
}
}
if let Some(a) = report.get("last_activity").and_then(Value::as_str) {
out.push_str(&format!("Last activity: {a}\n"));
}
let frames: Vec<&str> = report.get("backtrace").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).take(FRAMES).collect();
if !frames.is_empty() {
out.push_str("\nBacktrace (top):\n```\n");
for f in frames {
out.push_str(&without_home(f));
out.push('\n');
}
out.push_str("```\n");
}
out
}
/// The draft for `input`, by the [`version_line`] `version`.
pub fn draft(input: &Input, version: &str) -> Draft {
let crash = input.crash.as_ref();
let mut title = input.title.trim().to_string();
if title.is_empty() {
title = match crash.and_then(|c| c.get("kind")).and_then(Value::as_str) {
Some("unclean_exit") => "FieldCraft closed unexpectedly".to_string(),
Some(_) => "Internal error".to_string(),
None => match input.observed.trim().lines().next().filter(|l| !l.is_empty()) {
Some(line) => format!("Bug: {}", line.chars().take(100).collect::<String>()),
None => "Bug report".to_string(),
},
};
if let Some(c) = crash.and_then(|c| c.get("command")).and_then(|c| c.get("command")).and_then(Value::as_str) {
title.push_str(&format!(" in {c}"));
}
}
let title = cut(&without_home(&title), 200);
let mut observed = without_home(input.observed.trim());
if observed.is_empty()
&& let Some(m) = crash.and_then(|c| c.get("message")).and_then(Value::as_str)
{
observed = without_home(m);
}
let observed = cut(&observed, MAX_FIELD);
let share = input.share_session;
let mut evidence = crash.map(|c| crash_evidence(c, share)).unwrap_or_default();
let mut attachments = Vec::new();
let mut clipboard = None;
let mut reproduction = String::new();
// The session: the replayable script, from the attached model when there is one.
let model = input.model.as_ref().filter(|_| share && input.include_model);
let script = share.then(|| {
let mut steps = Vec::new();
if model.is_some() {
steps.push(json!({"command": "file.open", "params": {"path": MODEL_FILE}}));
}
steps.extend(input.commands.iter().cloned());
Value::Array(steps)
});
if let Some(m) = model {
attachments.push(Attachment { name: MODEL_FILE.into(), bytes: m.clone(), what: format!("the model ({} KB)", m.len().div_ceil(1024)) });
}
if let Some(script) = &script {
let n = script.as_array().map_or(0, Vec::len);
reproduction = format!("Replay the attached session ({n} command(s)): `fieldcraft-cli run {SESSION_FILE}`");
if model.is_some() {
reproduction.push_str(&format!(" in a folder holding `{MODEL_FILE}` too"));
} else if crash.is_some_and(|c| c.get("files").and_then(|f| f.get("model")).is_some()) {
reproduction.push_str(" (the crash replays from the model, which is not attached)");
}
reproduction.push('.');
}
let inline = |evidence: &str, script: &Value| {
let text = serde_json::to_string_pretty(script).unwrap_or_default();
format!("{evidence}\nSession ({SESSION_FILE}):\n```json\n{text}\n```\n")
};
let fields = |evidence: String| {
vec![("observed", observed.clone()), ("reproduction", reproduction.clone()), ("evidence", evidence), ("version", version.to_string())]
};
// The session in the link when it fits, else a file to attach (also on the clipboard).
let mut url = String::new();
if let Some(script) = &script {
let candidate = fields(inline(&evidence, script));
let u = link(&title, &candidate);
if u.len() <= MAX_URL {
evidence = inline(&evidence, script);
url = u;
} else {
let text = serde_json::to_string_pretty(script).unwrap_or_default();
evidence.push_str(&format!(
"\nThe session is too long for this form: FieldCraft saved it as `{SESSION_FILE}` and copied it to the clipboard. Attach the file here (drag it in) or paste it.\n"
));
attachments.insert(0, Attachment { name: SESSION_FILE.into(), bytes: text.clone().into_bytes(), what: "the session's commands".into() });
clipboard = Some(text);
}
}
if model.is_some() {
evidence.push_str(&format!("\nThe model is attached as `{MODEL_FILE}` (drag it in from the folder FieldCraft saved it to).\n"));
}
if url.is_empty() || model.is_some() {
let mut f = fields(evidence.clone());
url = link(&title, &f);
// Still too long (a very long message): cut the longest field until it fits.
while url.len() > MAX_URL {
let Some((i, len)) = f.iter().enumerate().map(|(i, (_, v))| (i, v.len())).max_by_key(|(_, l)| *l) else { break };
if len < 200 {
break;
}
if let Some((_, v)) = f.get_mut(i) {
*v = cut(v, len.saturating_sub(url.len() - MAX_URL + 64).min(len / 2 + 1));
}
url = link(&title, &f);
}
evidence = f.get(2).map(|(_, v)| v.clone()).unwrap_or_default();
}
let fields = fields(evidence);
// The fields as the link carries them (a cut field included).
let fields = if url == link(&title, &fields) { fields } else { decode_fields(&url) };
Draft { title, fields, url, attachments, clipboard }
}
/// Write a draft's attachments to `bug-reports/<time>/` in the app's data folder (the user
/// attaches them from there); returns the folder.
pub fn save_attachments(draft: &Draft) -> Result<std::path::PathBuf, String> {
let root = fieldcraft_io::recovery::data_dir().ok_or("no data folder on this system")?;
let dir = root.join("bug-reports").join(crate::crash::stamp_now());
fieldcraft_io::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
for a in &draft.attachments {
fieldcraft_io::fs::write_atomic(&dir.join(&a.name), &a.bytes, false).map_err(|e| e.to_string())?;
}
Ok(dir)
}
/// The fields a link carries (for the review, when a field had to be cut).
fn decode_fields(url: &str) -> Vec<(&'static str, String)> {
let query = url.split_once('?').map_or("", |(_, q)| q);
["observed", "reproduction", "evidence", "version"]
.into_iter()
.map(|k| {
let v = query.split('&').find_map(|kv| kv.strip_prefix(k).and_then(|r| r.strip_prefix('='))).unwrap_or_default();
(k, decode(v))
})
.collect()
}
fn decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while let Some(&c) = b.get(i) {
let hex = b.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok()).and_then(|h| u8::from_str_radix(h, 16).ok());
match (c, hex) {
(b'%', Some(v)) => {
out.push(v);
i += 3;
}
_ => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
fn home() -> String {
std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_else(|_| "/home/someone".into())
}
fn crash() -> Value {
json!({
"id": "20261014-101500-00000000deadbeef", "kind": "command_panic", "count": 2,
"message": format!("index out of bounds in {}/model.fieldcraft", home()),
"location": "crates/mesh/src/tet.rs:42",
"command": {"command": "mesh.tet.generate", "params": {"body": "Plate", "path": format!("{}/secret/plate.step", home())}},
"backtrace": ["fieldcraft_mesh::tet::insert (crates/mesh/src/tet.rs:42)"],
"files": {"model": "model.fieldcraft", "replay": "replay.json"},
})
}
#[test]
fn without_sharing_a_draft_names_no_paths_commands_or_model() {
let input = Input {
observed: format!("cannot open {}/parts/bracket.solidcraft", home()),
crash: Some(crash()),
commands: vec![json!({"command": "geometry.open", "params": {"path": format!("{}/parts/bracket.solidcraft", home())}})],
model: Some(b"model bytes".to_vec()),
include_model: true,
..Default::default()
};
let d = draft(&input, "v1.2.3, testos x");
assert!(d.url.starts_with("https://github.com/jyviko/fieldcraft/issues/new?template=bug.yml&title="), "{}", d.url);
assert!(d.attachments.is_empty() && d.clipboard.is_none(), "nothing attached without Share my session");
let all = format!("{} {:?} {}", d.title, d.fields, decode(&d.url));
assert!(!all.contains(&home()), "no home folder: {all}");
assert!(!all.contains("secret") && !all.contains("geometry.open"), "no parameters or commands: {all}");
assert!(all.contains("~/parts/bracket.solidcraft"), "the error, its home shown as ~: {all}");
assert!(all.contains("mesh.tet.generate") && all.contains("tet.rs:42") && all.contains("v1.2.3, testos x"), "{all}");
assert_eq!(d.title, "Internal error in mesh.tet.generate");
assert_eq!(decode_fields(&d.url), d.fields, "the review shows what the link carries");
}
#[test]
fn a_short_session_goes_in_the_link() {
let input = Input {
title: "Solve fails".into(),
share_session: true,
commands: vec![json!({"command": "file.sample", "params": {"name": "cantilever"}}), json!({"command": "solve.run", "params": {}})],
..Default::default()
};
let d = draft(&input, "v1");
assert!(d.attachments.is_empty() && d.clipboard.is_none());
let evidence = &d.fields.iter().find(|(k, _)| *k == "evidence").unwrap().1;
assert!(evidence.contains("\"command\": \"solve.run\""), "{evidence}");
assert!(d.url.len() <= MAX_URL);
assert!(decode(&d.url).contains("file.sample"));
}
#[test]
fn a_long_session_and_the_model_are_attachments() {
let commands: Vec<Value> = (0..400).map(|i| json!({"command": "mesh.node.add", "params": {"label": i + 1, "xyz": [i, 0, 0]}})).collect();
let input =
Input { share_session: true, include_model: true, commands, model: Some(vec![7; 3000]), crash: Some(crash()), ..Default::default() };
let d = draft(&input, "v1");
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
let names: Vec<&str> = d.attachments.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, [SESSION_FILE, MODEL_FILE]);
let session: Value = serde_json::from_slice(&d.attachments[0].bytes).unwrap();
assert_eq!(session[0], json!({"command": "file.open", "params": {"path": MODEL_FILE}}), "the replay opens the attached model");
assert_eq!(session.as_array().unwrap().len(), 401);
assert_eq!(d.clipboard.as_deref().map(str::as_bytes), Some(d.attachments[0].bytes.as_slice()));
let text = decode(&d.url);
assert!(text.contains("too long for this form") && text.contains(MODEL_FILE) && !text.contains("\"label\": 399"), "{text}");
// With the session shared, the crash's command parameters are shown (home as ~).
assert!(text.contains("~/secret/plate.step"), "{text}");
}
#[test]
fn a_huge_message_is_cut_to_fit_the_link() {
let input = Input { observed: "é".repeat(20_000), ..Default::default() };
let d = draft(&input, "v1");
assert!(d.url.len() <= MAX_URL, "{}", d.url.len());
assert!(d.fields[0].1.contains("[cut:"));
assert_eq!(decode_fields(&d.url), d.fields);
}
#[test]
fn encoding_round_trips() {
let s = "a b&c=d/é\n```json";
assert_eq!(decode(&encode(s)), s);
assert_eq!(encode("a b&"), "a%20b%26");
}
}
+134 -34
View File
@@ -155,6 +155,10 @@ pub struct Capability {
pub status: Status,
/// Related commands in the entry's drop-down (edit, delete…).
pub more: &'static [&'static str],
/// Commands the entry's own form covers (an option of it does the same), or that act on what
/// it makes from the browser's item menu (edit, delete): claimed by the entry for the command
/// search and the ribbon's stage, but not listed in the ribbon.
pub covers: &'static [&'static str],
}
impl Capability {
@@ -194,7 +198,7 @@ impl Capability {
}
const fn ready(id: &'static str, label: &'static str, tab: Tab, panel: &'static str, tip: &'static str) -> Capability {
Capability { id, label, tab, panel, tip, status: Status::Ready, more: &[] }
Capability { id, label, tab, panel, tip, status: Status::Ready, more: &[], covers: &[] }
}
const fn ready_more(
@@ -208,12 +212,23 @@ const fn ready_more(
Capability { more, ..ready(id, label, tab, panel, tip) }
}
const fn covering(
id: &'static str,
label: &'static str,
tab: Tab,
panel: &'static str,
tip: &'static str,
covers: &'static [&'static str],
) -> Capability {
Capability { covers, ..ready(id, label, tab, panel, tip) }
}
const fn soon(id: &'static str, label: &'static str, tab: Tab, panel: &'static str, milestone: &'static str, tip: &'static str) -> Capability {
Capability { id, label, tab, panel, tip, status: Status::Planned { milestone }, more: &[] }
Capability { id, label, tab, panel, tip, status: Status::Planned { milestone }, more: &[], covers: &[] }
}
const fn deck(id: &'static str, label: &'static str, format: &'static str, tip: &'static str) -> Capability {
Capability { id, label, tab: Tab::Solve, panel: "Decks", tip, status: Status::Deck { format, milestone: "M3" }, more: &[] }
Capability { id, label, tab: Tab::Solve, panel: "Decks", tip, status: Status::Deck { format, milestone: "M3" }, more: &[], covers: &[] }
}
use Tab::*;
@@ -232,12 +247,50 @@ pub static CATALOGUE: &[Capability] = &[
"Inspect",
"Weld, closed, manifold, orientation and self-intersection checks; feature edges",
),
soon("geometry.partition", "Partition", Geometry, "Prepare", "M5", "Split bodies and faces as SolidCraft features"),
soon("geometry.datum", "Datum Plane", Geometry, "Prepare", "M5", "Construction planes for partitions"),
// Edit and delete of datums and partitions are on the browser's item menu, not the ribbon.
covering(
"geometry.datum",
"Datum Plane",
Geometry,
"Prepare",
"A datum plane: principal plane and offset, three points or datum points, point and normal, normal to an axis",
&["geometry.datum.edit", "geometry.datum.delete"],
),
covering(
"geometry.datum.axis",
"Datum Axis",
Geometry,
"Prepare",
"A datum axis: principal axis, two points or datum points, point and direction",
&["geometry.datum.axis.edit"],
),
covering(
"geometry.datum.point",
"Datum Point",
Geometry,
"Prepare",
"A datum point: coordinates, a mesh vertex, along an edge, a face's centre, an axis through a plane",
&["geometry.datum.point.edit"],
),
covering(
"geometry.partition",
"Partition",
Geometry,
"Prepare",
"Cut bodies into cells by a datum plane; the two faces of each cut are paired by name",
&["geometry.partition.delete"],
),
soon("geometry.midsurface", "Midsurface", Geometry, "Prepare", "M8", "Extract midsurfaces of thin parts for shell meshes"),
// ---- Mesh ----
soon("mesh.size.global", "Global Size", Mesh, "Size", "M2", "One element size for the whole part"),
soon("mesh.size.seed", "Seed Edges", Mesh, "Size", "M2", "Element counts, sizes and bias per edge and face"),
ready_more(
"mesh.seed.edge",
"Seed Edges",
Mesh,
"Size",
"Element counts or sizes per design edge, with bias and an exact, minimum or free constraint; the meshers honour them",
&["mesh.seed.clear", "mesh.seed.list"],
),
soon("mesh.size.adapt", "Curvature", Mesh, "Size", "M2", "Refine by curvature and proximity"),
ready(
"mesh.tet.generate",
@@ -256,30 +309,30 @@ pub static CATALOGUE: &[Capability] = &[
"Quad or triangle mesh of a planar face or polygon in the XY plane for plane stress, plane strain and axisymmetric models; edges tagged",
),
soon("mesh.quad.faces", "Quad Faces", Mesh, "Structured Hex", "M5", "All-quad meshes of faces on shared edge nodes"),
ready_more(
"mesh.hex.mapped",
"Mapped Hex",
covering(
"mesh.hex.generate",
"Hex Mesh",
Mesh,
"Structured Hex",
"Mapped hex mesh of a six-sided block (curved faces allowed)",
&["mesh.hex.generate"],
"Structured hex mesh of a body: automatic, or extruded, swept, revolved or mapped (the Method drop-down)",
&["mesh.hex.sweep", "mesh.hex.mapped"],
),
ready_more(
"mesh.hex.sweep",
"Sweep Hex",
covering(
"mesh.cells",
"Partitioned Mesh",
Mesh,
"Structured Hex",
"Hex mesh swept along extrusions (several levels), around revolutions, or from a source face to a target",
&["mesh.hex.generate"],
"One mesh of a partitioned part, a method per cell (hex, tet, or all hex as conforming blocks); cells joined across partitions",
&["mesh.hex.blocks"],
),
ready(
"mesh.hex.blocks",
"Block Hex",
soon(
"mesh.hex.decompose",
"Decompose",
Mesh,
"Structured Hex",
"One conforming hex mesh of a part split into six-sided blocks: shared faces meshed once",
"M5",
"Find sweepable and mappable regions of 3D parts (extruded cross-sections are already cut into blocks by Hex Mesh)",
),
soon("mesh.hex.decompose", "Decompose", Mesh, "Structured Hex", "M5", "Find sweepable and mappable regions and propose the splits"),
soon("mesh.transition", "Transition", Mesh, "Structured Hex", "M5", "Conforming tet–hex interfaces with pyramids"),
ready(
"mesh.hex.octree",
@@ -300,7 +353,7 @@ pub static CATALOGUE: &[Capability] = &[
Mesh,
"Edit",
"Add an element on existing nodes, or a mapped block of them",
&["mesh.element.remove", "mesh.block"],
&["mesh.element.remove", "mesh.block", "mesh.mirror"],
),
soon("mesh.node.merge", "Merge Nodes", Mesh, "Edit", "M6", "Merge coincident nodes"),
soon("mesh.region.remesh", "Remesh Region", Mesh, "Edit", "M6", "Remesh a region in place; split and collapse elements"),
@@ -372,7 +425,7 @@ pub static CATALOGUE: &[Capability] = &[
Loads,
"Boundary Conditions",
"Fixed, displacement or symmetry condition on a set or reference point",
&["model.boundary_condition.edit", "model.boundary_condition.delete"],
&["model.boundary_condition.edit", "model.boundary_condition.delete", "model.boundary_condition.symmetry"],
),
ready_more(
"model.load.create",
@@ -414,22 +467,29 @@ pub static CATALOGUE: &[Capability] = &[
"Kinematic or distributing coupling of a set to a reference point",
&["model.coupling.edit", "model.coupling.delete"],
),
soon("interaction.tie", "Tie", Interactions, "Constraints", "M7", "Tie non-matching meshes together"),
ready_more(
"interaction.tie",
"Tie",
Interactions,
"Constraints",
"Tie non-matching meshes together (dual mortar constraints)",
&["interaction.tie.edit", "interaction.tie.delete"],
),
ready_more(
"interaction.contact.general",
"General Contact",
Interactions,
"Contact",
"Contact between everything that may touch, or self contact of a surface, with friction (explicit dynamics)",
"Contact between everything that may touch, or self contact of a surface, with friction (explicit dynamics and nonlinear static steps)",
&["interaction.contact.edit", "interaction.contact.delete"],
),
ready_more(
// Its edit and delete rows are General Contact's: they act on contacts of either kind.
ready(
"interaction.contact.pair",
"Contact Pair",
Interactions,
"Contact",
"Contact between two surfaces, with friction (explicit dynamics)",
&["interaction.contact.edit", "interaction.contact.delete"],
"Contact between two surfaces: with friction in explicit dynamics, mortar contact with friction in nonlinear static steps",
),
ready(
"interaction.contact.find",
@@ -527,8 +587,25 @@ pub static CATALOGUE: &[Capability] = &[
"Open a model autosaved by an app that crashed or closed with unsaved changes",
&["file.recovery.list", "file.recovery.discard"],
),
// Hide, show and isolate act on the browser's items, from their eyes and item menus.
covering(
"view.show_all",
"Show All",
Tools,
"View",
"Show every item hidden in the viewport (hide, show and isolate items from the browser)",
&["view.hide", "view.show", "view.isolate"],
),
ready("edit.undo", "Undo", Tools, "History", "Undo the last command that changed the model"),
ready("edit.redo", "Redo", Tools, "History", "Redo the command undone last"),
ready_more(
"diagnostics.bug_report",
"Report a Bug",
Tools,
"Help",
"Draft a GitHub bug report with the version, the OS and the last error; you review it, and nothing is sent until you submit it",
&["diagnostics.crash_reports", "diagnostics.crash_report", "diagnostics.crash_test", "app.update.check"],
),
];
/// The catalogue entry with this id.
@@ -537,9 +614,12 @@ pub fn find(id: &str) -> Option<&'static Capability> {
}
/// The entry that claims a command: the one running it, else the one listing it among its
/// related commands. Every registered command has one (a test checks it).
/// related commands or covering it. Every registered command has one (a test checks it).
pub fn entry_of(command: &str) -> Option<&'static Capability> {
CATALOGUE.iter().find(|c| c.command() == Some(command)).or_else(|| CATALOGUE.iter().find(|c| c.more.contains(&command)))
CATALOGUE
.iter()
.find(|c| c.command() == Some(command))
.or_else(|| CATALOGUE.iter().find(|c| c.more.contains(&command) || c.covers.contains(&command)))
}
/// The tab the ribbon follows to when `command` has run from anywhere but the ribbon (a script,
@@ -582,7 +662,8 @@ pub fn features_page() -> String {
let preset = c.preset();
let main =
c.command().map(|id| if preset.as_object().is_some_and(|o| !o.is_empty()) { format!("`{id} {preset}`") } else { format!("`{id}`") });
let commands: Vec<String> = main.into_iter().chain(c.more.iter().map(|id| format!("`{id}`"))).collect();
let commands: Vec<String> =
main.into_iter().chain(c.more.iter().map(|id| format!("`{id}`"))).chain(c.covers.iter().map(|id| format!("(`{id}`)"))).collect();
let _ = writeln!(md, "| {} | {} — {} | {status} | {} |", c.panel, c.label, c.tip, commands.join(", "));
}
}
@@ -612,6 +693,25 @@ mod tests {
}
}
/// Each command has one place in the ribbon: no two menu rows (an entry or a drop-down row)
/// run the same command with the same preset, and a command an entry's form covers is no row.
#[test]
fn no_command_appears_twice_across_ribbon_menus() {
let mut rows: Vec<String> = Vec::new();
for c in CATALOGUE {
let entry = c.command().map(|id| format!("{id} {}", c.preset()));
for row in entry.into_iter().chain(c.more.iter().map(|id| format!("{id} {{}}"))) {
assert!(!rows.contains(&row), "{}: `{row}` is in the ribbon twice", c.id);
rows.push(row);
}
}
for c in CATALOGUE {
for m in c.covers {
assert!(!rows.iter().any(|r| r.split(' ').next() == Some(m)), "{}: `{m}` is covered by its form and also a ribbon row", c.id);
}
}
}
#[test]
fn the_ribbon_follows_each_command_to_its_stage() {
assert_eq!(stage_tab("mesh.hex.sweep"), Some(Tab::Mesh));
@@ -626,7 +726,7 @@ mod tests {
assert_eq!(stage_tab("no.such"), None);
// A ribbon click (an entry's command, or one of its drop-down's) stays on the tab shown.
for c in CATALOGUE {
for command in c.command().into_iter().chain(c.more.iter().copied()) {
for command in c.command().into_iter().chain(c.more.iter().copied()).chain(c.covers.iter().copied()) {
assert!(stage_tab(command).is_none_or(|t| t == c.tab), "{}: `{command}` would move the ribbon from {:?}", c.id, c.tab);
}
}
@@ -640,9 +740,9 @@ mod tests {
assert!(find_command(command).is_some(), "{}: `{command}` is not a registered command", c.id);
claimed.push(command);
} else {
assert!(c.more.is_empty(), "{}: a planned entry has no commands", c.id);
assert!(c.more.is_empty() && c.covers.is_empty(), "{}: a planned entry has no commands", c.id);
}
for m in c.more {
for m in c.more.iter().chain(c.covers) {
assert!(find_command(m).is_some(), "{}: `{m}` is not a registered command", c.id);
claimed.push(m);
}
+2 -1
View File
@@ -20,6 +20,7 @@ pub const BLOCK: CommandSpec = CommandSpec {
params: r#"{"body": "Plate", "kind": "hex8|hex20|tet4|tet10|wedge6", "corners": [[x, y, z] × 8] (hex8 order: 1-2-3-4 counter-clockwise seen from 5-6-7-8), "divisions": [n12, n14, n15] (elements along 1→2, 1→4, 1→5), "bias": [1, 1, 1] (optional: last over first element size along each direction), "edges": [{"corners": [1, 2], "arc": {"center": [x, y, z]}} | {"corners": [2, 3], "ellipse": {"center": [x, y, z], "axes": [[a], [b]] (perpendicular)}} | {"corners": [5, 6], "name": "tip_edge"}] (optional: curved edges, the shorter arc between the corners, and edge names), "faces": {"1": "bottom", "4": "tip"} (optional: names of block faces, numbered as hex8 faces: 1 = 1-2-3-4, 2 = 5-6-7-8, 3 = 1-2-6-5, 4 = 2-3-7-6, 5 = 3-4-8-7, 6 = 4-1-5-8), "vertices": {"1": "A"} (optional: names of corners), "merge": distance (optional, default 1e-6 of the block's diagonal; 0 never joins)} — adds a mapped mesh of the block (transfinite interpolation of its edges; quadratic nodes on the curves), uses existing nodes within `merge` of new ones so blocks that share a face join (the shared face must have the same elements on both sides, or nothing changes), and tags the elements with the body and element faces, edges and nodes with the named faces, edges and vertices. 2D: "kind": "quad4|quad8|tri3|tri6", four "corners" at z = 0 (counter-clockwise from +z), "divisions": [n12, n14], "bias": [r, r], "face": "area" (the face of the body the elements fill, default `area`), edges and vertices numbered among the four corners; for plane stress, plane strain and axisymmetric sections"#,
form: Some(super::forms::BLOCK),
kind: CommandKind::Model,
requires: &[],
run: block_mesh,
};
@@ -108,7 +109,7 @@ fn block_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let region = match (planar, &p.face) {
(true, face) => GeometryRef::face(p.body.clone(), face.clone().unwrap_or_else(|| "area".into()))?,
(false, None) => GeometryRef::body(p.body.clone())?,
(false, Some(_)) => return Err(EngineError::Params("`face` names the region of 2D elements; a solid block fills its body".into())),
(false, Some(_)) => return Err(EngineError::invalid("face", "names the region of 2D elements; a solid block fills its body")),
};
if planar && !p.faces.is_empty() {
return Err(EngineError::Params("a 2D patch has no faces to name: name its edges".into()));
+494
View File
@@ -0,0 +1,494 @@
//! Meshing a partitioned part cell by cell (`mesh.cells`): each cell (a body of the open design,
//! typically made by `geometry.partition`) with its own method, all into one mesh, and the cells
//! joined across the partitions that divide them.
//!
//! **Joining.** Two cells on either side of a partition `P` meet on faces named
//! `partition:P:a` and `partition:P:b`. Where the element faces of the two sides match node for
//! node (the same divisions and kind on both sides, e.g. a mesh and its mirror image) the
//! coincident nodes are merged and the mesh is conforming there. Elsewhere — a hex cell next to a
//! tet cell, or two cells meshed with different divisions — the two surfaces are tied: a set on
//! each side's partition faces and a tie between them (`interaction.tie`; dual mortar
//! constraints in the implicit analyses, so a constant stress crosses the interface exactly).
//! The tie is the transition between hex and tet cells; pyramid elements are not used, because
//! they need their own element formulation in every solver and deck, while the tie works for any
//! pair of meshes and keeps each cell's mesh as its method made it. The reply lists every
//! interface and how it was joined.
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_mesh::cdt::CdtOptions;
use fieldcraft_mesh::hex::{HexMesh, HexMethod};
use fieldcraft_model::geometry::Entity;
use fieldcraft_model::{ElementFace, GeometryRef, Model, Set, Tie};
use serde_json::{Value, json};
use super::hex::{Input, add_hex, hex_body};
use super::mesh::{BodyTets, add_tets, mesh_body, quality_options};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const CELLS: CommandSpec = CommandSpec {
id: "mesh.cells",
label: "Partitioned Mesh",
params: r#"{"methods": {"Body1/a": "tet", "Body1/b": "swept"} (per cell; default `default`), "default": "auto", "bodies": ["Body1/a", "Body1/b"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 | 2 (hex8 and tet4, or hex20 and tet10), "tolerance": 0.05 (chordal tolerance, mm)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one mesh of the cells, each with its method: "auto" (structured hex where a method fits, else tet), "hex" (any structured hex method), "swept", "extrude", "sweep", "revolve", "mapped" or "tet"; or "default": "blocks" (with no `methods`): every cell a mapped block, division counts assigned over all cells together, exactly mesh.hex.blocks with the same parameters. Cells on either side of a partition (faces `partition:<name>:a` and `:b`) are joined: where their element faces match node for node the nodes are merged (conforming); otherwise, as between a hex and a tet cell, a set on each side and a tie between them are made (`tie_<partition>_<k>`, sets `<tie>_main` and `<tie>_secondary`: the side with fewer nodes is the main surface), replacing ties of those names from an earlier run. Reports each cell's method (and why auto fell back to tet), and each interface: `merged` with the nodes merged, or `tied`"#,
form: Some(super::forms::CELLS),
kind: CommandKind::Model,
requires: &[Requirement::Design],
run: cells,
};
/// Distance (relative to the cells' bounding-box diagonal) within which interface nodes coincide.
const COINCIDENT: f64 = 1e-7;
/// A cell's method.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Method {
Auto,
Hex(HexMethod),
Tet,
}
impl Method {
fn parse(v: &Value) -> Result<Method> {
let name = v.as_str().unwrap_or_default();
Ok(match name {
"auto" => Method::Auto,
"hex" => Method::Hex(HexMethod::Auto),
"tet" => Method::Tet,
_ => match HexMethod::from_name(name).filter(|m| *m != HexMethod::Auto) {
Some(m) => Method::Hex(m),
None => {
return Err(EngineError::Params(format!(
"method `{}` is not one of auto, hex, swept, extrude, sweep, revolve, mapped, tet",
name.chars().take(40).collect::<String>()
)));
}
},
})
}
}
/// A meshed cell.
enum Meshed<'a> {
Hex(Input<'a>, HexMesh),
Tet(BodyTets),
}
fn cells(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("default").and_then(Value::as_str) == Some("blocks") {
if p.get("methods").is_some_and(|m| m.as_object().is_none_or(|o| !o.is_empty())) {
return Err(EngineError::param(
"methods",
crate::schema::ProblemKind::Invalid("must be empty with \"default\": \"blocks\" (every cell a block)".into()),
));
}
return super::hex::hex_blocks(s, p);
}
let size = super::hex::number(p, "size")?;
let quadratic = match p.get("order") {
None => false,
Some(v) => match v.as_u64() {
Some(1) => false,
Some(2) => true,
_ => return Err(EngineError::invalid("order", "must be 1 or 2")),
},
};
let default = p.get("default").map(Method::parse).transpose()?.unwrap_or(Method::Auto);
let methods: BTreeMap<String, Method> = match p.get("methods") {
None => BTreeMap::new(),
Some(Value::Object(m)) => m.iter().map(|(k, v)| Ok((k.clone(), Method::parse(v)?))).collect::<Result<_>>()?,
Some(_) => return Err(EngineError::invalid("methods", "must map cell names to methods")),
};
let design = s.design.clone().ok_or_else(|| EngineError::Params("open a design first".into()))?;
let names: Vec<String> = match p.get("bodies") {
None => design.bodies.iter().map(|b| b.name.clone()).collect(),
Some(_) => super::req(p, "bodies")?,
};
if names.is_empty() || names.len() > fieldcraft_mesh::hex::MAX_CELLS {
return Err(EngineError::Params(format!("{} cells; mesh.cells meshes 1 to {}", names.len(), fieldcraft_mesh::hex::MAX_CELLS)));
}
for n in methods.keys() {
if !names.contains(n) {
return Err(EngineError::Params(format!("`methods` names `{n}`, which is not a cell being meshed")));
}
}
// One size and tolerance from the cells' joint extent, as mesh.hex.blocks does.
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
let mut shapes = Vec::with_capacity(names.len());
for (i, n) in names.iter().enumerate() {
if names.get(..i).is_some_and(|b| b.contains(n)) {
return Err(EngineError::Params(format!("cell `{n}` is listed twice")));
}
let shape = design.body(n).ok_or_else(|| EngineError::Params(format!("no body `{n}`")))?;
let m = shape.measure()?;
for k in 0..3 {
lo[k] = lo[k].min(m.bbox_min[k]);
hi[k] = hi[k].max(m.bbox_max[k]);
}
shapes.push(shape);
}
let diagonal = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::<f64>().sqrt();
if !(diagonal > 0.0 && diagonal.is_finite()) {
return Err(EngineError::Params("the cells have no extent".into()));
}
let size = Some(size.unwrap_or(diagonal / 25.0));
let tolerance = super::hex::number(p, "tolerance")?.unwrap_or(1e-3 * diagonal);
// The tet mesher's parameters: the same size and tolerance, its own order names.
let mut tet_params = json!({"size": size, "tolerance": tolerance, "order": if quadratic { "quadratic" } else { "linear" }});
for key in ["weld", "weld_distance", "feature_angle"] {
if let (Some(v), Some(o)) = (p.get(key), tet_params.as_object_mut()) {
o.insert(key.into(), v.clone());
}
}
let mut hex_params = tet_params.clone();
if let Some(o) = hex_params.as_object_mut() {
o.remove("order");
}
let (tet_options, quality) = quality_options(&tet_params, s.limits.max_tets as u64)?;
let cdt = CdtOptions { max_steiner: s.limits.max_steiner, max_tets: tet_options.max_tets };
let seeds = super::seeds::edge_seeds(s)?;
let mut meshed: Vec<(Meshed, Value)> = Vec::with_capacity(shapes.len());
for shape in shapes {
let method = methods.get(&shape.name).copied().unwrap_or(default);
let input = || Ok::<_, EngineError>(Input { seeds: seeds.clone(), ..super::hex::shape_input(shape, Some(tolerance))? });
let hex = |m: HexMethod| -> Result<(Input<'static>, HexMesh)> {
let b = input()?;
let mesh = hex_body(&hex_params, &b, m, quadratic, size)?;
Ok((b, mesh))
};
let tet = |s: &Session| mesh_body(s, &tet_params, input()?, &cdt, &tet_options, quality, true);
let (cell, mut info) = match method {
Method::Hex(m) => {
let (b, mesh) = hex(m)?;
let info = json!({"method": mesh.report.method.name()});
(Meshed::Hex(b, mesh), info)
}
Method::Tet => (Meshed::Tet(tet(s)?), json!({"method": "tet"})),
Method::Auto => match hex(HexMethod::Auto) {
Ok((b, mesh)) => {
let info = json!({"method": mesh.report.method.name()});
(Meshed::Hex(b, mesh), info)
}
Err(e) => (Meshed::Tet(tet(s)?), json!({"method": "tet", "why": e.to_string()})),
},
};
if let Some(o) = info.as_object_mut() {
o.insert("body".into(), json!(shape.name));
}
meshed.push((cell, info));
}
// Replace the cells' meshes (replace.rs), each after the labels before it; other bodies
// and the definitions stay.
let model = &mut s.model;
let cleared = super::replace::clear(model, names.iter().map(String::as_str));
let mut report = Vec::with_capacity(meshed.len());
for (cell, mut info) in meshed {
let (kind, elements, nodes) = match &cell {
Meshed::Hex(b, m) => {
add_hex(model, b, m)?;
(m.kind, m.element_count(), m.nodes.len())
}
Meshed::Tet(t) => {
add_tets(model, &t.name, &t.face_names, &t.mesh)?;
(t.mesh.kind, t.mesh.elements.len(), t.mesh.points.len())
}
};
if let Some(o) = info.as_object_mut() {
o.insert("kind".into(), json!(kind.name()));
o.insert("elements".into(), json!(elements));
o.insert("nodes".into(), json!(nodes));
}
report.push(info);
}
let interfaces = join(model, &names, COINCIDENT * diagonal)?;
let (nodes, elements) = (model.nodes().len(), model.elements().len());
Ok(cleared.report(s, json!({"cells": report, "interfaces": interfaces, "nodes": nodes, "elements": elements, "size": size})))
}
/// One side of an interface: a cell's element faces on one side of a partition.
struct Side {
body: String,
/// The face name (`partition:P:a`), which selects its pieces too.
face: String,
faces: Vec<ElementFace>,
nodes: BTreeSet<u32>,
lo: [f64; 3],
hi: [f64; 3],
}
/// The element faces of each cell tagged with a partition's cut faces, by partition and side.
fn sides(model: &Model, cells: &[String]) -> BTreeMap<String, [Vec<Side>; 2]> {
let c = model.classification();
// Tag → (partition, side), for cut faces of the meshed cells.
let mut cut: BTreeMap<u32, (String, usize, String)> = BTreeMap::new();
for (t, r) in c.entities().iter().enumerate() {
let Entity::Face(name) = &r.entity else { continue };
if !cells.contains(&r.body) {
continue;
}
let base = name.split_once('#').map_or(name.as_str(), |(b, _)| b);
let Some(rest) = base.strip_prefix("partition:") else { continue };
let Some((partition, side)) = rest.rsplit_once(':') else { continue };
let side = match side {
"a" => 0,
"b" => 1,
_ => continue,
};
if let Ok(t) = u32::try_from(t) {
cut.insert(t, (partition.to_string(), side, r.body.clone()));
}
}
let mut grouped: BTreeMap<(String, usize, String), Vec<ElementFace>> = BTreeMap::new();
for (&element, tags) in c.elements() {
for (&face, t) in &tags.faces {
if let Some(key) = cut.get(t) {
grouped.entry(key.clone()).or_default().push(ElementFace { element, face });
}
}
}
let mut out: BTreeMap<String, [Vec<Side>; 2]> = BTreeMap::new();
for ((partition, side, body), faces) in grouped {
let nodes: BTreeSet<u32> = faces.iter().filter_map(|f| model.face_nodes(*f)).flatten().collect();
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for n in nodes.iter().filter_map(|&n| model.node(n)) {
for k in 0..3 {
lo[k] = lo[k].min(n.xyz[k]);
hi[k] = hi[k].max(n.xyz[k]);
}
}
let face = format!("partition:{partition}:{}", if side == 0 { "a" } else { "b" });
if let Some(slot) = out.entry(partition).or_insert_with(|| [Vec::new(), Vec::new()]).get_mut(side) {
slot.push(Side { body, face, faces, nodes, lo, hi });
}
}
out
}
/// Join the cells across every partition: merge where the two sides match node for node, tie
/// where they do not. Returns the interfaces.
fn join(model: &mut Model, cells: &[String], tol: f64) -> Result<Vec<Value>> {
let mut out = Vec::new();
for (partition, [a_sides, b_sides]) in sides(model, cells) {
let mut k = 0;
for a in &a_sides {
for b in &b_sides {
let overlap = (0..3).all(|i| a.lo[i] <= b.hi[i] + tol && b.lo[i] <= a.hi[i] + tol);
if !overlap {
continue;
}
k += 1;
let matched = matching(model, a, b, tol);
if let Some(map) = matched {
let count = map.len();
model.merge_nodes(&map)?;
out.push(json!({"partition": partition, "cells": [a.body, b.body], "joined": "merged", "nodes": count}));
} else {
let name = format!("tie_{partition}_{k}");
let (main, secondary) = if a.nodes.len() <= b.nodes.len() { (a, b) } else { (b, a) };
let set = |side: &Side| -> Result<Set> { Ok(Set::of_geometry(vec![GeometryRef::face(side.body.as_str(), side.face.as_str())?])) };
let (main_set, secondary_set) = (format!("{name}_main"), format!("{name}_secondary"));
for (n, side) in [(&main_set, main), (&secondary_set, secondary)] {
if model.set(n).is_some() {
model.replace_set(n, set(side)?)?;
} else {
model.add_set(n, set(side)?)?;
}
}
if model.tie(&name).is_some() {
model.remove_tie(&name)?;
}
model.add_tie(&name, Tie::new(&main_set, &secondary_set))?;
out.push(json!({
"partition": partition,
"cells": [a.body, b.body],
"joined": "tied",
"tie": name,
"main": main.body,
"secondary": secondary.body,
"faces": [a.faces.len(), b.faces.len()],
}));
}
}
}
}
Ok(out)
}
/// When the two sides' nodes coincide one to one (within `tol`) and their faces are the same
/// in number, the merge: each node of side `b` to the node of side `a` at its place (or the other
/// way round, so the lower label survives).
fn matching(model: &Model, a: &Side, b: &Side, tol: f64) -> Option<BTreeMap<u32, u32>> {
if a.nodes.len() != b.nodes.len() || a.faces.len() != b.faces.len() {
return None;
}
let both: BTreeSet<u32> = a.nodes.union(&b.nodes).copied().collect();
let map = fieldcraft_mesh::join::coincident_nodes(model, Some(&both), tol).ok()?;
// Every pair joins one node of each side, and every node of either side is in a pair.
let one_to_one = map.len() == a.nodes.len()
&& map.iter().all(|(from, to)| (a.nodes.contains(from) && b.nodes.contains(to)) || (b.nodes.contains(from) && a.nodes.contains(to)));
one_to_one.then_some(map)
}
#[cfg(test)]
mod tests {
use super::*;
/// The sample plate (40 × 30 × 10, a Ø10 hole at (15, 15)) open and cut at x = 30, right of
/// the hole: `Body1/a` holds the hole, `Body1/b` is a 10 × 30 × 10 block.
fn cut_plate() -> (crate::tests::TempDir, Session) {
let (dir, path) = crate::tests::sample_design_file(&fieldcraft_geometry::sample::Plate::default());
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
(dir, s)
}
#[test]
fn hex_and_tet_cells_are_tied_and_matching_hex_cells_merged() {
let (_dir, mut s) = cut_plate();
// A tet cell next to a hex cell: tied, main the coarser side.
let r = s.execute("mesh.cells", &json!({"methods": {"Body1/a": "tet", "Body1/b": "mapped"}, "size": 2.5})).unwrap();
assert_eq!(r["cells"][0]["kind"], "tet4", "{r}");
assert_eq!(r["cells"][1]["kind"], "hex8", "{r}");
let i = &r["interfaces"][0];
assert_eq!(i["joined"], "tied", "{r}");
assert_eq!(s.model.ties().len(), 1);
for set in ["tie_P_1_main", "tie_P_1_secondary"] {
assert!(s.model.resolve_set(set).unwrap().faces.len() > 4, "{set}");
}
// Both cells hex at one size: the plane faces match node for node and merge.
let r = s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
assert_eq!(r["interfaces"].as_array().map(Vec::len), Some(1), "{r}");
let i = &r["interfaces"][0];
assert_eq!(i["joined"], "merged", "{r}");
let separate = r["cells"].as_array().unwrap().iter().map(|c| c["nodes"].as_u64().unwrap()).sum::<u64>();
assert_eq!(r["nodes"].as_u64().unwrap() + i["nodes"].as_u64().unwrap(), separate, "{r}");
// Rerunning replaces the tie it made rather than adding another.
s.execute("mesh.cells", &json!({"methods": {"Body1/a": "tet"}, "size": 2.5})).unwrap();
assert_eq!(s.model.ties().len(), 1);
}
/// The half crank arm (cut on its symmetry plane only) has no cell that maps or sweeps as
/// the design gives it; the extrusion decomposes its cross-section into blocks itself, alike
/// through mesh.hex.generate (auto) and mesh.cells, with no seeds.
#[test]
fn the_half_crank_extrudes_in_blocks_without_partitions() {
let bytes = fieldcraft_geometry::script_design(crate::sample::CRANK_ARM).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Sym"})).unwrap();
let r = s.execute("mesh.hex.generate", &json!({"body": "CrankArm/a", "size": 3})).unwrap();
let body = &r["bodies"][0];
assert_eq!(body["method"], "extrude", "{r}");
assert!(body["description"].as_str().unwrap().contains(" 0 free)"), "{r}");
assert!(body["quality"]["min_scaled_jacobian"].as_f64().unwrap() >= 0.37, "{r}");
let r = s.execute("mesh.cells", &json!({"bodies": ["CrankArm/a"], "default": "extrude", "size": 3})).unwrap();
assert_eq!(r["cells"][0]["method"], "extrude", "{r}");
assert_eq!(r["elements"], body["elements"], "{r}");
}
#[test]
fn auto_falls_back_to_tet_and_says_why() {
let (_dir, mut s) = cut_plate();
let r = s.execute("mesh.cells", &json!({"default": "mapped", "methods": {"Body1/a": "auto"}, "size": 3})).unwrap();
// The holed cell is not a mapped block, but auto sweeps it.
assert!(r["cells"][0]["method"].as_str().is_some(), "{r}");
assert_eq!(r["cells"][1]["method"], "mapped", "{r}");
}
#[test]
fn hostile_params_change_nothing() {
let (_dir, mut s) = cut_plate();
let journal = s.journal.len();
for p in [
json!({"default": "pyramid"}),
json!({"methods": {"Nope": "tet"}}),
json!({"methods": ["tet"]}),
json!({"bodies": []}),
json!({"bodies": ["Body1/a", "Body1/a"]}),
json!({"bodies": ["Nope"]}),
json!({"order": 3}),
json!({"size": -1}),
json!({"default": "mapped", "bodies": ["Body1/a"]}),
] {
assert!(s.execute("mesh.cells", &p).is_err(), "{p}");
}
assert_eq!(s.journal.len(), journal);
assert!(s.model.elements().is_empty());
}
/// A 40 × 10 × 10 bar in uniaxial tension, cut in the middle: one half hex, the other tet,
/// tied. With ν = 0, symmetry conditions on three faces and the end load spread by consistent
/// weights, the stress is uniform, which both elements and the dual mortar tie carry exactly:
/// the end moves F L / (E A).
#[test]
fn a_tied_hex_tet_bar_in_tension_stretches_as_the_formula_says() {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
]});
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
let bbox = s.execute("geometry.bodies", &json!({})).unwrap()[0]["bbox"].clone();
let lo: Vec<f64> = bbox[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let hi: Vec<f64> = bbox[1].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let (axis, length) = (0..3).map(|k| (k, hi[k] - lo[k])).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap();
assert!((length - 40.0).abs() < 1e-9);
let mid = (lo[axis] + hi[axis]) / 2.0;
let mut normal = [0.0; 3];
normal[axis] = 1.0;
let mut point = [0.0; 3];
point[axis] = mid;
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "point_normal", "point": point, "normal": normal}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Cut", "datum": "Mid"})).unwrap();
let r = s.execute("mesh.cells", &json!({"methods": {"Bar/a": "mapped", "Bar/b": "tet"}, "size": 2.5})).unwrap();
assert_eq!(r["interfaces"][0]["joined"], "tied", "{r}");
let m = &s.model;
let on = |k: usize, v: f64| -> Vec<u32> { m.nodes().iter().filter(|(_, n)| (n.xyz[k] - v).abs() < 1e-9).map(|(l, _)| *l).collect() };
let others: Vec<usize> = (0..3).filter(|k| *k != axis).collect();
let end: Vec<Value> = m
.elements()
.iter()
.flat_map(|(&e, el)| (1..=el.kind.faces().len() as u8).map(move |f| (e, f)))
.filter(|&(e, f)| {
m.face_nodes(ElementFace { element: e, face: f })
.is_some_and(|ns| ns.iter().all(|n| (m.node(*n).unwrap().xyz[axis] - hi[axis]).abs() < 1e-9))
})
.map(|(e, f)| json!({"element": e, "face": f}))
.collect();
let plane = |k: usize| ["x", "y", "z"][k];
let (young, area, force) = (70_000.0, 100.0, 1000.0);
let script = json!([
{"command": "model.set.create", "params": {"name": "all", "elements": m.elements().keys().collect::<Vec<_>>()}},
{"command": "model.set.create", "params": {"name": "root", "nodes": on(axis, lo[axis])}},
{"command": "model.set.create", "params": {"name": "side1", "nodes": on(others[0], lo[others[0]])}},
{"command": "model.set.create", "params": {"name": "side2", "nodes": on(others[1], lo[others[1]])}},
{"command": "model.set.create", "params": {"name": "end", "faces": end}},
{"command": "model.material.create", "params": {"name": "Al", "elastic": {"type": "isotropic", "young": young, "poisson": 0}}},
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Al", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "s0", "type": "symmetry", "target": {"set": "root"}, "plane": plane(axis)}},
{"command": "model.boundary_condition.create", "params": {"name": "s1", "type": "symmetry", "target": {"set": "side1"}, "plane": plane(others[0])}},
{"command": "model.boundary_condition.create", "params": {"name": "s2", "type": "symmetry", "target": {"set": "side2"}, "plane": plane(others[1])}},
{"command": "model.load.create", "params": {"name": "Pull", "type": "force", "target": {"set": "end"}, "vector": normal.map(|n| n * force)}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["s0", "s1", "s2"], "loads": ["Pull"]}},
]);
let tip = on(axis, hi[axis]);
s.run_script(&script).unwrap();
s.execute("solve.static", &json!({})).unwrap();
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip})).unwrap();
let expected = force * length / (young * area);
let probed = probe["nodes"].as_array().unwrap();
assert!(probed.len() > 4, "{probe}");
for n in probed {
let u = n["displacement"][axis].as_f64().unwrap();
assert!((u - expected).abs() < 1e-6 * expected, "{u} vs {expected}: {n}");
}
}
}
+92 -8
View File
@@ -1,7 +1,8 @@
//! `interaction.contact.*`: contact definitions (pairs of surfaces, general contact) and the
//! search for surfaces that touch.
//! search for surfaces that touch; `interaction.tie*`: ties between non-matching meshes.
//!
//! A contact's surfaces are sets of element faces ([`fieldcraft_model::contact`]). The commands
//! A contact's surfaces are sets of element faces, or of element edges in a 2D model
//! ([`fieldcraft_model::contact`]). The commands
//! take the friction, penalty scale and initial-penetration choice of the model's form; `edit`
//! replaces a definition with the model's JSON form, `delete` removes it.
//!
@@ -11,13 +12,15 @@
//! touch there. Each touching pair is reported with the faces of each side that are close to the
//! other; with `create`, each becomes two face sets and a contact pair.
use crate::schema::ProblemKind;
use std::collections::BTreeMap;
use fieldcraft_fem::contact::{Grid, bounds, closest_point};
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialPenetration, Model, Set};
use fieldcraft_model::{Contact, ContactSurfaces, ElementFace, Friction, InitialPenetration, Model, Set, Tie};
use serde_json::{Value, json};
use super::{name, opt};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
/// The options every contact takes, from the parameters.
@@ -32,7 +35,7 @@ fn contact(p: &Value, surfaces: ContactSurfaces) -> Result<Contact> {
/// A required name-valued parameter.
fn text<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::Params(format!("`{key}` must be a set name")))
p.get(key).and_then(Value::as_str).ok_or_else(|| EngineError::param(key, ProblemKind::NotAName))
}
pub const PAIR: CommandSpec = CommandSpec {
@@ -40,11 +43,12 @@ pub const PAIR: CommandSpec = CommandSpec {
label: "Contact Pair",
params: concat!(
r#"{"name": "impact", "main": "plate" (a set of element faces), "secondary": "ball" (another), "#,
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the stiffest penalty that leaves the time increment alone), "initial_penetration": "adjust" (move nodes that start inside onto the surface, strain-free, and report them) | "refuse" (refuse the analysis, naming the first)"#,
r#"} — contact between two surfaces, each one's nodes kept out of the other's faces (explicit dynamics; fails if the name is taken)"#
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the penalty: explicit, the stiffest that leaves the time increment alone; nonlinear static, the augmented Lagrangian's), "initial_penetration": "adjust" (nodes that start inside: explicit moves them onto the surface, strain-free; nonlinear static takes the overlap out of their gap; both report them) | "refuse" (refuse the analysis, naming the first)"#,
r#"} — contact between two surfaces: in explicit dynamics each one's nodes are kept out of the other's faces; in nonlinear static steps `secondary` is the mortar (non-mortar) side whose pressure field is enforced against `main` by an augmented Lagrangian, with Coulomb friction by a return map (static coefficient while a node sticks, kinetic once it slips) (fails if the name is taken)"#
),
form: Some(super::forms::CONTACT_PAIR),
kind: CommandKind::Model,
requires: &[Requirement::Set],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
let surfaces = ContactSurfaces::Pair { main: text(p, "main")?.to_string(), secondary: text(p, "secondary")?.to_string() };
@@ -58,11 +62,12 @@ pub const GENERAL: CommandSpec = CommandSpec {
label: "General Contact",
params: concat!(
r#"{"name": "all", "surface": "skin" (optional: a set of element faces, each in contact with every other: self contact; default every exterior face of the solids), "#,
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the stiffest penalty that leaves the time increment alone), "initial_penetration": "adjust" (move nodes that start inside onto the surface, strain-free, and report them) | "refuse" (refuse the analysis, naming the first)"#,
r#"} — single-surface contact of everything that may touch (explicit dynamics; fails if the name is taken)"#
r#""friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb, μ = μk + (μs − μk) e^(−decay × slip rate); default frictionless), "penalty_scale": 1 (0 < scale ≤ 1: a factor on the penalty: explicit, the stiffest that leaves the time increment alone; nonlinear static, the augmented Lagrangian's), "initial_penetration": "adjust" (nodes that start inside: explicit moves them onto the surface, strain-free; nonlinear static takes the overlap out of their gap; both report them) | "refuse" (refuse the analysis, naming the first)"#,
r#"} — single-surface contact of everything that may touch (explicit dynamics, and mortar self-contact in nonlinear static steps; fails if the name is taken)"#
),
form: Some(super::forms::CONTACT_GENERAL),
kind: CommandKind::Model,
requires: &[],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
let surface = match p.get("surface") {
@@ -80,6 +85,7 @@ pub const EDIT: CommandSpec = CommandSpec {
params: r#"{"name": "impact", "surfaces": {"type": "pair", "main": "plate", "secondary": "ball"} | {"type": "general", "surface": "skin" (optional)}, "friction": {…}, "penalty_scale": 1, "initial_penetration": "adjust|refuse"} — replaces the contact of that name (the model's form; see interaction.contact.pair)"#,
form: Some(super::forms::CONTACT_EDIT),
kind: CommandKind::Model,
requires: &[Requirement::Contact],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
let mut obj = p.as_object().cloned().ok_or_else(|| EngineError::Params("the parameters of a contact are a JSON object".into()))?;
@@ -96,12 +102,63 @@ pub const DELETE: CommandSpec = CommandSpec {
params: r#"{"name": "impact"}"#,
form: Some(super::forms::CONTACT_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Contact],
run: |s: &mut Session, p: &Value| {
s.model.remove_contact(name(p)?)?;
Ok(Value::Null)
},
};
/// A tie from the parameters.
fn tie(p: &Value) -> Result<Tie> {
Ok(Tie {
main: text(p, "main")?.to_string(),
secondary: text(p, "secondary")?.to_string(),
position_tolerance: opt::<f64>(p, "position_tolerance")?,
})
}
pub const TIE: CommandSpec = CommandSpec {
id: "interaction.tie",
label: "Tie",
params: r#"{"name": "glue", "main": "plate" (a set of element faces), "secondary": "rib" (another), "position_tolerance": 0.1 (optional: how far a secondary node may lie from the main surface and still be tied; default half the main element's thickness)} — bonds the secondary surface to the main one across non-matching meshes: each secondary node follows the main surface under it (dual mortar constraints in the implicit analyses; a constant stress crosses the tie exactly); fails if the name is taken"#,
form: Some(super::forms::TIE),
kind: CommandKind::Model,
requires: &[Requirement::Set],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
s.model.add_tie(n, tie(p)?)?;
Ok(json!({"name": n}))
},
};
pub const TIE_EDIT: CommandSpec = CommandSpec {
id: "interaction.tie.edit",
label: "Edit Tie",
params: r#"{"name": "glue", "main": "plate", "secondary": "rib", "position_tolerance": 0.1} — replaces the tie of that name (see interaction.tie)"#,
form: Some(super::forms::TIE_EDIT),
kind: CommandKind::Model,
requires: &[Requirement::Tie],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
s.model.replace_tie(n, tie(p)?)?;
Ok(json!({"name": n}))
},
};
pub const TIE_DELETE: CommandSpec = CommandSpec {
id: "interaction.tie.delete",
label: "Delete Tie",
params: r#"{"name": "glue"}"#,
form: Some(super::forms::TIE_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Tie],
run: |s: &mut Session, p: &Value| {
s.model.remove_tie(name(p)?)?;
Ok(Value::Null)
},
};
pub const FIND: CommandSpec = CommandSpec {
id: "interaction.contact.find",
label: "Find Contacts",
@@ -111,6 +168,7 @@ pub const FIND: CommandSpec = CommandSpec {
),
form: Some(super::forms::CONTACT_FIND),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: find,
};
@@ -334,6 +392,32 @@ mod tests {
assert!(s.model.contacts().is_empty());
}
#[test]
fn ties_are_created_edited_and_deleted() {
let mut s = Session::default();
stacked(&mut s);
s.execute("model.set.create", &json!({"name": "a", "faces": [{"element": 5, "face": 2}]})).unwrap();
s.execute("model.set.create", &json!({"name": "b", "faces": [{"element": 9, "face": 1}]})).unwrap();
s.execute("interaction.tie", &json!({"name": "glue", "main": "a", "secondary": "b"})).unwrap();
assert_eq!(s.model.tie("glue"), Some(&Tie::new("a", "b")));
for bad in [
json!({"name": "glue", "main": "a", "secondary": "b"}),
json!({"name": "x", "main": "a", "secondary": "a"}),
json!({"name": "x", "main": "a", "secondary": "nope"}),
json!({"name": "x", "main": "a", "secondary": "b", "position_tolerance": -1}),
json!({"name": "x", "main": "a", "secondary": "b", "position_tolerance": "far"}),
json!({"name": "x", "main": 3, "secondary": "b"}),
] {
assert!(s.execute("interaction.tie", &bad).is_err(), "{bad}");
}
s.execute("interaction.tie.edit", &json!({"name": "glue", "main": "b", "secondary": "a", "position_tolerance": 0.01})).unwrap();
assert_eq!(s.model.tie("glue").and_then(|t| t.position_tolerance), Some(0.01));
assert!(s.execute("interaction.tie.edit", &json!({"name": "nope", "main": "a", "secondary": "b"})).is_err());
assert!(s.execute("model.set.delete", &json!({"name": "a"})).unwrap_err().to_string().contains("tie `glue`"));
s.execute("interaction.tie.delete", &json!({"name": "glue"})).unwrap();
assert!(s.model.ties().is_empty() && s.execute("interaction.tie.delete", &json!({"name": "glue"})).is_err());
}
#[test]
fn find_reports_and_creates_the_touching_parts() {
let mut s = Session::default();
+730
View File
@@ -0,0 +1,730 @@
//! Datum planes, axes and points, and partitions of the open design by datum planes.
//!
//! Datums and partitions are part of the model (`fieldcraft_model::datums`). A datum point is
//! placed by coordinates, at a mesh vertex, along a design edge, at a design face's centre or
//! where a datum axis crosses a datum plane; planes and axes can be made through datum points.
//! Each takes the coordinates of what it is made from when it is made (a later edit of a datum
//! point leaves the planes and axes made through it where they are). A partition cuts the
//! design in memory (`fieldcraft_geometry::partition`); the model's partitions are applied again,
//! in order, whenever the design is opened (`geometry.open`, `file.open`, samples), so an edit
//! of the design followed by a re-open replays them.
use crate::schema::ProblemKind;
use std::sync::Arc;
use fieldcraft_geometry::{Cut, Design};
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
use fieldcraft_model::{Datum, Model, Partition};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const DATUM_PLANE: CommandSpec = CommandSpec {
id: "geometry.datum",
label: "Datum Plane",
params: r#"{"name": "Mid", "by": {"type": "offset", "plane": "yz" | "zx" | "xy", "offset": 15} | {"type": "three_points", "a": [x, y, z], "b": […], "c": […]} | {"type": "point_normal", "point": [x, y, z], "normal": [nx, ny, nz]} | {"type": "datum_points", "a": "P1", "b": "P2", "c": "P3"} | {"type": "normal_to_axis", "axis": "Spindle", "point"?: "P1"}} — a named datum plane (model coordinates, mm for SolidCraft geometry): a principal plane moved along its normal (yz: normal +x, zx: normal +y, xy: normal +z), through three points or three datum points (normal (b − a) × (c − a)), through a point with a normal, or normal to a datum axis through a datum point (the axis's point by default). Partitions (geometry.partition) cut by it; shown in the viewport"#,
form: Some(super::forms::DATUM_PLANE),
kind: CommandKind::Model,
requires: &[],
run: datum_plane,
};
pub const DATUM_AXIS: CommandSpec = CommandSpec {
id: "geometry.datum.axis",
label: "Datum Axis",
params: r#"{"name": "Spindle", "by": {"type": "principal", "axis": "x" | "y" | "z", "through"?: [x, y, z] (default the origin)} | {"type": "two_points", "a": [x, y, z], "b": […]} | {"type": "point_direction", "point": [x, y, z], "direction": [dx, dy, dz]} | {"type": "datum_points", "a": "P1", "b": "P2"}} — a named datum axis, shown in the viewport"#,
form: Some(super::forms::DATUM_AXIS),
kind: CommandKind::Model,
requires: &[],
run: datum_axis,
};
pub const DATUM_POINT: CommandSpec = CommandSpec {
id: "geometry.datum.point",
label: "Datum Point",
params: r#"{"name": "P1", "by": {"type": "coordinates", "point": [x, y, z]} | {"type": "vertex", "body": "Body1", "vertex": "v3"} | {"type": "edge", "body": "Body1", "edge": "F1:top|F2:side", "fraction"?: 0.5} | {"type": "face_centre", "body": "Body1", "face": "F2:top"} | {"type": "axis_plane", "axis": "Spindle", "plane": "Mid"}} — a named datum point, shown in the viewport as a small cross: at coordinates, at a vertex of the mesh (as its geometry tags name it), a fraction along an edge of the open design (0.5: its midpoint), at the area centre of a face of the open design, or where a datum axis crosses a datum plane. Datum planes and axes can be made through datum points"#,
form: Some(super::forms::DATUM_POINT),
kind: CommandKind::Model,
requires: &[],
run: datum_point,
};
pub const DATUM_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.edit",
label: "Edit Datum Plane",
params: r#"{"name": "Mid", "by": …} — redefines a datum plane (the parameters of geometry.datum); the partitions that cut by it cut again"#,
form: Some(super::forms::DATUM_PLANE),
kind: CommandKind::Model,
requires: &[Requirement::DatumPlane],
run: |s, p| datum_edit(s, p, "plane"),
};
pub const DATUM_AXIS_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.axis.edit",
label: "Edit Datum Axis",
params: r#"{"name": "Spindle", "by": …} — redefines a datum axis (the parameters of geometry.datum.axis)"#,
form: Some(super::forms::DATUM_AXIS),
kind: CommandKind::Model,
requires: &[Requirement::DatumAxis],
run: |s, p| datum_edit(s, p, "axis"),
};
pub const DATUM_POINT_EDIT: CommandSpec = CommandSpec {
id: "geometry.datum.point.edit",
label: "Edit Datum Point",
params: r#"{"name": "P1", "by": …} — redefines a datum point (the parameters of geometry.datum.point); planes and axes made through it stay where they are"#,
form: Some(super::forms::DATUM_POINT),
kind: CommandKind::Model,
requires: &[Requirement::DatumPoint],
run: |s, p| datum_edit(s, p, "point"),
};
pub const DATUM_DELETE: CommandSpec = CommandSpec {
id: "geometry.datum.delete",
label: "Delete Datum",
params: r#"{"name": "Mid", "cascade"?: false} — deletes a datum plane, axis or point; one a partition cuts by is refused (naming the partitions), unless `cascade` deletes those partitions too"#,
form: Some(super::forms::DATUM_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Datum],
run: datum_delete,
};
pub const PARTITION: CommandSpec = CommandSpec {
id: "geometry.partition",
label: "Partition",
params: r#"{"name": "Half", "datum": "Mid", "bodies"?: ["Body1"] (default: every body the plane divides)} — cuts bodies of the open design into cells by a datum plane, in memory (the design file is not changed); the model keeps the partition and applies it again whenever the design is opened, after the partitions before it. A cut body `B` becomes the cells `B/a` (on the plane's negative side) and `B/b` (several pieces on a side: `B/a1`, `B/a2`, …). The two faces of the cut are paired by name: `partition:<name>:a` on the cells on the negative side, `partition:<name>:b` on the positive side (`…#0`, `…#1` where a cell has several); every other face keeps the persistent name of the face it is a piece of (`<face>#k` for several pieces on one cell), so sets by face name still select it. Reports the cells made and the cut faces named; a plane that divides no body, or a listed body it does not divide, is an error"#,
form: Some(super::forms::PARTITION),
kind: CommandKind::Model,
requires: &[Requirement::Design, Requirement::DatumPlane],
run: partition,
};
pub const PARTITION_DELETE: CommandSpec = CommandSpec {
id: "geometry.partition.delete",
label: "Delete Partition",
params: r#"{"name": "Half"} — removes a partition; the design is cut again by the ones left"#,
form: Some(super::forms::PARTITION_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Partition],
run: partition_delete,
};
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Principal {
Yz,
Zx,
Xy,
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum PlaneBy {
Offset {
plane: Principal,
#[serde(default)]
offset: f64,
},
ThreePoints {
a: [f64; 3],
b: [f64; 3],
c: [f64; 3],
},
PointNormal {
point: [f64; 3],
normal: [f64; 3],
},
DatumPoints {
a: String,
b: String,
c: String,
},
NormalToAxis {
axis: String,
#[serde(default)]
point: Option<String>,
},
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Axis {
X,
Y,
Z,
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum AxisBy {
Principal {
axis: Axis,
#[serde(default)]
through: [f64; 3],
},
TwoPoints {
a: [f64; 3],
b: [f64; 3],
},
PointDirection {
point: [f64; 3],
direction: [f64; 3],
},
DatumPoints {
a: String,
b: String,
},
}
fn half() -> f64 {
0.5
}
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum PointBy {
Coordinates {
point: [f64; 3],
},
Vertex {
body: String,
vertex: String,
},
Edge {
body: String,
edge: String,
#[serde(default = "half")]
fraction: f64,
},
FaceCentre {
body: String,
face: String,
},
AxisPlane {
axis: String,
plane: String,
},
}
fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
/// The coordinates of datum point `name`.
fn datum_point_at(m: &Model, name: &str) -> Result<[f64; 3]> {
match m.datum(name) {
Some(d) => d.point().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not a point", d.kind()))),
None => Err(EngineError::Params(format!("no datum point `{name}`"))),
}
}
/// The point and unit direction of datum axis `name`.
fn datum_axis_of(m: &Model, name: &str) -> Result<([f64; 3], [f64; 3])> {
match m.datum(name) {
Some(d) => d.axis().ok_or_else(|| EngineError::Params(format!("datum `{name}` is a datum {}, not an axis", d.kind()))),
None => Err(EngineError::Params(format!("no datum axis `{name}`"))),
}
}
/// A plane through three points; collinear points are refused relative to their spread.
fn three_points(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> Result<Datum> {
let (u, v) = (sub(b, a), sub(c, a));
let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let size = u.iter().chain(&v).map(|x| x * x).sum::<f64>();
if !(n.iter().map(|x| x * x).sum::<f64>() > 1e-20 * size * size) {
return Err(EngineError::Params("the three points must not lie on one line".into()));
}
Ok(Datum::Plane { point: a, normal: n })
}
fn plane_datum(m: &Model, by: PlaneBy) -> Result<Datum> {
Ok(match by {
PlaneBy::Offset { plane, offset } => {
if !offset.is_finite() {
return Err(EngineError::param("offset", ProblemKind::NotANumber));
}
let normal = match plane {
Principal::Yz => [1.0, 0.0, 0.0],
Principal::Zx => [0.0, 1.0, 0.0],
Principal::Xy => [0.0, 0.0, 1.0],
};
Datum::Plane { point: normal.map(|n| n * offset), normal }
}
PlaneBy::ThreePoints { a, b, c } => three_points(a, b, c)?,
PlaneBy::PointNormal { point, normal } => Datum::Plane { point, normal },
PlaneBy::DatumPoints { a, b, c } => three_points(datum_point_at(m, &a)?, datum_point_at(m, &b)?, datum_point_at(m, &c)?)?,
PlaneBy::NormalToAxis { axis, point } => {
let (on_axis, direction) = datum_axis_of(m, &axis)?;
let point = match point {
Some(p) => datum_point_at(m, &p)?,
None => on_axis,
};
Datum::Plane { point, normal: direction }
}
})
}
fn axis_datum(m: &Model, by: AxisBy) -> Result<Datum> {
Ok(match by {
AxisBy::Principal { axis, through } => {
let direction = match axis {
Axis::X => [1.0, 0.0, 0.0],
Axis::Y => [0.0, 1.0, 0.0],
Axis::Z => [0.0, 0.0, 1.0],
};
Datum::Axis { point: through, direction }
}
AxisBy::TwoPoints { a, b } => Datum::Axis { point: a, direction: sub(b, a) },
AxisBy::PointDirection { point, direction } => Datum::Axis { point, direction },
AxisBy::DatumPoints { a, b } => {
let a = datum_point_at(m, &a)?;
Datum::Axis { point: a, direction: sub(datum_point_at(m, &b)?, a) }
}
})
}
/// Most mesh nodes a vertex is looked for among.
const MAX_VERTEX_NODES: usize = 10_000_000;
fn point_datum(s: &Session, by: PointBy) -> Result<Datum> {
let shape = |body: &str| -> Result<&fieldcraft_geometry::Shape> {
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
design.body(body).ok_or_else(|| EngineError::Params(format!("the design has no body `{body}`")))
};
let point = match by {
PointBy::Coordinates { point } => point,
PointBy::Vertex { body, vertex } => {
let m = &s.model;
let at = fieldcraft_model::GeometryRef::new(body.clone(), fieldcraft_model::Entity::Vertex(vertex.clone()))?;
let tags = m.classification().tags_selected_by(&at);
let node =
m.classification().nodes().iter().take(MAX_VERTEX_NODES).find(|(_, t)| tags.contains(t)).and_then(|(n, _)| m.node(*n)).ok_or_else(
|| EngineError::Params(format!("vertex `{vertex}` of body `{body}` is on no mesh node (vertices are named on meshed bodies)")),
)?;
node.xyz
}
PointBy::Edge { body, edge, fraction } => {
if !(0.0..=1.0).contains(&fraction) {
return Err(EngineError::invalid("fraction", "is a number from 0 to 1".to_string()));
}
let edges = shape(&body)?.edges()?;
let e = edges.iter().find(|e| e.name == edge).ok_or_else(|| EngineError::Params(format!("body `{body}` has no edge `{edge}`")))?;
e.point_at(fraction).ok_or_else(|| EngineError::Params(format!("edge `{edge}` of body `{body}` has no points")))?
}
PointBy::FaceCentre { body, face } => shape(&body)?.face_centre(&face)?,
PointBy::AxisPlane { axis, plane } => {
let (p, d) = datum_axis_of(&s.model, &axis)?;
let (q, n) = match s.model.datum(&plane) {
Some(x) => x.plane().ok_or_else(|| EngineError::Params(format!("datum `{plane}` is a datum {}, not a plane", x.kind())))?,
None => return Err(EngineError::Params(format!("no datum plane `{plane}`"))),
};
let along = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
let across = along(d, n);
// Unit vectors: the sine of the angle between the axis and the plane.
if across.abs() < 1e-9 {
return Err(EngineError::Params(format!("axis `{axis}` is parallel to plane `{plane}`: they do not cross")));
}
let t = along(sub(q, p), n) / across;
[p[0] + t * d[0], p[1] + t * d[1], p[2] + t * d[2]]
}
};
Ok(Datum::Point { point })
}
/// The datum `by` defines for a datum of `kind` (`plane`, `axis` or `point`).
fn datum_of(s: &Session, kind: &str, p: &Value) -> Result<Datum> {
match kind {
"plane" => plane_datum(&s.model, super::req(p, "by")?),
"axis" => axis_datum(&s.model, super::req(p, "by")?),
_ => point_datum(s, super::req(p, "by")?),
}
}
/// The parameters of the command that edits datum `name`, describing it as it is (a plane by
/// its point and normal, an axis by its point and direction, a point by its coordinates); and
/// that command.
pub fn edit_params(name: &str, d: &Datum) -> (&'static str, Value) {
match *d {
Datum::Plane { point, normal } => (DATUM_EDIT.id, json!({"name": name, "by": {"type": "point_normal", "point": point, "normal": normal}})),
Datum::Axis { point, direction } => {
(DATUM_AXIS_EDIT.id, json!({"name": name, "by": {"type": "point_direction", "point": point, "direction": direction}}))
}
Datum::Point { point } => (DATUM_POINT_EDIT.id, json!({"name": name, "by": {"type": "coordinates", "point": point}})),
}
}
fn datum_json(name: &str, d: &Datum) -> Value {
let mut v = serde_json::to_value(d).unwrap_or(Value::Null);
if let Some(o) = v.as_object_mut() {
o.insert("name".into(), json!(name));
}
v
}
fn datum_create(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let name = super::name(p)?;
let datum = datum_of(s, kind, p)?;
s.model.add_datum(name, datum)?;
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
}
fn datum_plane(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "plane")
}
fn datum_axis(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "axis")
}
fn datum_point(s: &mut Session, p: &Value) -> Result<Value> {
datum_create(s, p, "point")
}
/// Redefine datum `name` of `kind`; the partitions that cut by a plane cut again.
fn datum_edit(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
let name = super::name(p)?;
match s.model.datum(name) {
Some(d) if d.kind() == kind => {}
Some(d) => return Err(EngineError::Params(format!("datum `{name}` is a datum {}, not a {kind}", d.kind()))),
None => return Err(EngineError::Params(format!("no datum {kind} `{name}`"))),
}
let datum = datum_of(s, kind, p)?;
s.model.replace_datum(name, datum)?;
if !s.model.datum_users(name).is_empty() {
recut(s)?;
}
Ok(datum_json(name, s.model.datum(name).unwrap_or(&datum)))
}
fn datum_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
let cascade: bool = super::opt(p, "cascade")?.unwrap_or(false);
let partitions: Vec<String> = s.model.partitions().iter().filter(|x| x.datum == name).map(|x| x.name.clone()).collect();
if cascade {
for partition in &partitions {
s.model.remove_partition(partition)?;
}
}
s.model.remove_datum(name)?;
if cascade && !partitions.is_empty() {
recut(s)?;
}
Ok(json!({"deleted": name, "partitions": if cascade { partitions } else { Vec::new() }}))
}
/// The model's partitions as cuts of the geometry.
fn cuts(model: &Model) -> Vec<Cut> {
model
.partitions()
.iter()
.filter_map(|p| {
let (point, normal) = model.datum(&p.datum)?.plane()?;
Some(Cut { name: p.name.clone(), point, normal, bodies: p.bodies.clone() })
})
.collect()
}
/// `design` cut by `model`'s partitions (the design as opened when the model has none).
pub(crate) fn partitioned(design: &Design, model: &Model) -> Result<Design> {
Ok(design.partitioned(&cuts(model))?)
}
/// Cut the session's design by its model's partitions again.
fn recut(s: &mut Session) -> Result<()> {
if let Some(d) = &s.design {
let cut = partitioned(d, &s.model)?;
s.design = Some(Arc::new(cut));
}
Ok(())
}
fn partition(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?.to_string();
let datum: String = super::req(p, "datum")?;
let bodies: Vec<String> = super::opt(p, "bodies")?.unwrap_or_default();
s.model.add_partition(Partition { name: name.clone(), datum: datum.clone(), bodies })?;
recut(s)?;
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
let feature = format!("partition {name}");
let errors: Vec<&str> = design.errors.iter().filter(|e| e.feature == feature).map(|e| e.message.as_str()).collect();
if !errors.is_empty() {
return Err(EngineError::Params(format!("partition `{name}`: {}", errors.join("; "))));
}
let report = design.cuts.iter().find(|c| c.name == name);
let split = report.map(|r| r.split.clone()).unwrap_or_default();
if split.is_empty() {
return Err(EngineError::Params(format!("partition `{name}`: the plane divides no body of the design")));
}
let cells: Vec<String> = design.bodies.iter().map(|b| b.name.clone()).filter(|b| split.iter().any(|x| b.starts_with(&format!("{x}/")))).collect();
let (faces, bodies): (usize, Vec<String>) = (report.map_or(0, |r| r.faces), design.bodies.iter().map(|b| b.name.clone()).collect());
// The cut shows as edges on the cells, so the plane steps out of the way (view state, #295):
// selecting it in the browser or its eye shows it again.
if s.view.hidden.len() < MAX_HIDDEN {
s.view.hidden.insert(Item { kind: ItemKind::Datum, name: datum });
}
Ok(json!({
"name": name,
"split": split,
"cells": cells,
"cut_faces": faces,
"bodies": bodies,
}))
}
fn partition_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?;
s.model.remove_partition(name)?;
recut(s)?;
let bodies: Vec<String> = s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect();
Ok(json!({"deleted": name, "bodies": bodies}))
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
/// A session with the sample plate (40 × 30 × 10, Ø10 hole at (15, 15)) open.
pub(crate) fn plate() -> (Session, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("fieldcraft-partition-{}-{:?}", std::process::id(), std::thread::current().id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plate.solidcraft");
let plate = fieldcraft_geometry::sample::Plate::default();
std::fs::write(&path, fieldcraft_geometry::sample::plate_design(&plate).unwrap()).unwrap();
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path.to_str().unwrap()})).unwrap();
(s, dir)
}
fn bodies(s: &Session) -> Vec<String> {
s.design.as_ref().unwrap().bodies.iter().map(|b| b.name.clone()).collect()
}
#[test]
fn datums_by_each_definition() {
let mut s = Session::default();
let r = s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
assert_eq!(r, json!({"name": "Mid", "type": "plane", "point": [15.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0]}));
let r = s
.execute("geometry.datum", &json!({"name": "Tri", "by": {"type": "three_points", "a": [0, 0, 1], "b": [1, 0, 1], "c": [0, 1, 1]}}))
.unwrap();
assert_eq!(r["normal"], json!([0.0, 0.0, 1.0]));
s.execute("geometry.datum", &json!({"name": "Tilt", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 3, 4]}})).unwrap();
assert_eq!(s.model.datum("Tilt"), Some(&Datum::Plane { point: [0.0; 3], normal: [0.0, 0.6, 0.8] }));
let r = s.execute("geometry.datum.axis", &json!({"name": "Z", "by": {"type": "principal", "axis": "z", "through": [1, 2, 0]}})).unwrap();
assert_eq!(r, json!({"name": "Z", "type": "axis", "point": [1.0, 2.0, 0.0], "direction": [0.0, 0.0, 1.0]}));
s.execute("geometry.datum.axis", &json!({"name": "D", "by": {"type": "two_points", "a": [0, 0, 0], "b": [0, 2, 0]}})).unwrap();
s.execute("geometry.datum.axis", &json!({"name": "E", "by": {"type": "point_direction", "point": [0, 0, 0], "direction": [5, 0, 0]}}))
.unwrap();
assert_eq!(s.model.datums().len(), 6);
s.execute("geometry.datum.delete", &json!({"name": "D"})).unwrap();
assert_eq!(s.model.datums().len(), 5);
}
#[test]
fn hostile_datum_params_change_nothing() {
let mut s = Session::default();
for p in [
json!({}),
json!({"name": "A"}),
json!({"name": "A", "by": {"type": "offset", "plane": "ab"}}),
json!({"name": "A", "by": {"type": "offset", "plane": "xy", "offset": "x"}}),
json!({"name": "A", "by": {"type": "three_points", "a": [0, 0, 0], "b": [1, 1, 1], "c": [2, 2, 2]}}),
json!({"name": "A", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 0, 0]}}),
json!({"name": "A", "by": {"type": "point_normal", "point": [1e300, 0, 0], "normal": [0, 0, 1]}}),
json!({"name": "A", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [0, 0, 1], "extra": 1}}),
json!({"name": "1A", "by": {"type": "offset", "plane": "xy"}}),
json!({"name": "A", "by": {"type": "nope"}}),
] {
assert!(s.execute("geometry.datum", &p).is_err(), "{p}");
}
for p in [
json!({"name": "A", "by": {"type": "two_points", "a": [1, 1, 1], "b": [1, 1, 1]}}),
json!({"name": "A", "by": {"type": "principal", "axis": "w"}}),
] {
assert!(s.execute("geometry.datum.axis", &p).is_err(), "{p}");
}
assert!(s.model.datums().is_empty());
assert!(s.journal.is_empty());
}
#[test]
fn a_partition_cuts_the_design_and_is_replayed_when_it_opens_again() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
let r = s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
let body = r["split"][0].as_str().unwrap().to_string();
assert_eq!(r["cells"], json!([format!("{body}/a"), format!("{body}/b")]));
assert_eq!(r["cut_faces"], json!(4));
// The datum is in use, and hidden: the cut shows as edges on the cells (#295). Its eye
// shows it again.
assert!(s.execute("geometry.datum.delete", &json!({"name": "Mid"})).is_err());
assert!(!s.shows(ItemKind::Datum, "Mid"));
s.execute("view.show", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
assert!(s.shows(ItemKind::Datum, "Mid"));
s.execute("view.hide", &json!({"items": [{"kind": "datum", "name": "Mid"}]})).unwrap();
// A set on a cut face selects the cut face's pieces.
let r = s.execute("geometry.bodies", &json!({})).unwrap();
let faces: Vec<&str> = r[0]["faces"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect();
assert!(faces.contains(&"partition:Half:a#0"), "{faces:?}");
// Saved and opened again: the design is cut again by the model's partition.
let file = dir.join("plate.fieldcraft");
s.execute("file.save_as", &json!({"path": file.to_str().unwrap()})).unwrap();
let mut t = Session::default();
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
assert_eq!(bodies(&t), bodies(&s));
assert!(!t.shows(ItemKind::Datum, "Mid"), "still hidden when opened again");
// geometry.open again keeps the model, so its partition.
let design = dir.join("plate.solidcraft");
let r = t.execute("geometry.open", &json!({"path": design.to_str().unwrap()})).unwrap();
assert_eq!(r["bodies"], json!(bodies(&s)));
// A new model drops the partitions with the rest of the model.
let r = t.execute("geometry.open", &json!({"path": design.to_str().unwrap(), "model": "new"})).unwrap();
assert_eq!(r["bodies"], json!([body]));
// Undo brings the whole design back; deleting the partition does too.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(bodies(&s), std::slice::from_ref(&body));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(bodies(&s).len(), 2);
s.execute("geometry.partition.delete", &json!({"name": "Half"})).unwrap();
assert_eq!(bodies(&s), [body]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn datum_points_by_each_definition_and_planes_and_axes_through_them() {
let (mut s, dir) = plate();
let point = |s: &Session, n: &str| s.model.datum(n).and_then(Datum::point).unwrap();
let close = |a: [f64; 3], b: [f64; 3]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6);
s.execute("geometry.datum.point", &json!({"name": "O", "by": {"type": "coordinates", "point": [0, 0, 0]}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "X", "by": {"type": "coordinates", "point": [10, 0, 0]}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "Y", "by": {"type": "coordinates", "point": [0, 10, 0]}})).unwrap();
// The plate's edge along x at y = 0, z = 0, its midpoint and a quarter along it.
let body = s.design.as_ref().unwrap().bodies[0].clone();
let edge = body.edges().unwrap().into_iter().find(|e| e.points.iter().all(|p| p[1].abs() < 1e-9 && p[2].abs() < 1e-9)).unwrap();
let by = |fraction: f64| json!({"type": "edge", "body": body.name, "edge": edge.name, "fraction": fraction});
s.execute("geometry.datum.point", &json!({"name": "Mid", "by": {"type": "edge", "body": body.name, "edge": edge.name}})).unwrap();
assert!(close(point(&s, "Mid"), [20.0, 0.0, 0.0]), "{:?}", point(&s, "Mid"));
s.execute("geometry.datum.point", &json!({"name": "Q", "by": by(0.25)})).unwrap();
let q = point(&s, "Q");
assert!((q[0] - 10.0).abs() < 1e-6 || (q[0] - 30.0).abs() < 1e-6, "{q:?}");
// The centre of the face at x = 0.
let side =
body.face_surfaces().unwrap().iter().position(
|f| matches!(f, Some(fieldcraft_geometry::FaceSurface::Plane { normal, point }) if normal[0] < -0.5 && point[0].abs() < 1e-9),
);
let face = body.faces()[side.unwrap()].name.clone();
s.execute("geometry.datum.point", &json!({"name": "C", "by": {"type": "face_centre", "body": body.name, "face": face}})).unwrap();
assert!(close(point(&s, "C"), [0.0, 15.0, 5.0]), "{:?}", point(&s, "C"));
// Planes and axes through datum points; a point where an axis crosses a plane.
let r = s.execute("geometry.datum", &json!({"name": "Base", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Y"}})).unwrap();
assert_eq!(r["normal"], json!([0.0, 0.0, 1.0]));
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "datum_points", "a": "O", "b": "X"}})).unwrap();
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [1.0, 0.0, 0.0] }));
s.execute("geometry.datum", &json!({"name": "Cut", "by": {"type": "normal_to_axis", "axis": "Ax", "point": "Mid"}})).unwrap();
assert_eq!(s.model.datum("Cut"), Some(&Datum::Plane { point: point(&s, "Mid"), normal: [1.0, 0.0, 0.0] }));
s.execute("geometry.datum.point", &json!({"name": "Hit", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Cut"}})).unwrap();
assert!(close(point(&s, "Hit"), [20.0, 0.0, 0.0]));
let journal = s.journal.len();
for p in [
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Ax", "plane": "Base"}}),
json!({"name": "Z", "by": {"type": "axis_plane", "axis": "Base", "plane": "Cut"}}),
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": edge.name, "fraction": 2}}),
json!({"name": "Z", "by": {"type": "edge", "body": body.name, "edge": "nope"}}),
json!({"name": "Z", "by": {"type": "edge", "body": "Nope", "edge": edge.name}}),
json!({"name": "Z", "by": {"type": "face_centre", "body": body.name, "face": "nope"}}),
// No mesh: no vertex is named.
json!({"name": "Z", "by": {"type": "vertex", "body": body.name, "vertex": "v1"}}),
json!({"name": "Z", "by": {"type": "coordinates", "point": [f64::MAX, 0, 0]}}),
json!({"name": "Z", "by": {"type": "coordinates", "point": [0, 0]}}),
] {
assert!(s.execute("geometry.datum.point", &p).is_err(), "{p}");
}
for (command, p) in [
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Mid"}})),
("geometry.datum", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "X", "c": "Ax"}})),
("geometry.datum", json!({"name": "Z", "by": {"type": "normal_to_axis", "axis": "Nope"}})),
("geometry.datum.axis", json!({"name": "Z", "by": {"type": "datum_points", "a": "O", "b": "O"}})),
] {
assert!(s.execute(command, &p).is_err(), "{p}");
}
assert_eq!(s.journal.len(), journal);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_vertex_point_is_at_the_tagged_mesh_node() {
let mut s = Session::default();
s.execute(
"mesh.block",
&json!({"body": "Bar", "kind": "hex8", "corners": [[0,0,0],[4,0,0],[4,1,0],[0,1,0],[0,0,1],[4,0,1],[4,1,1],[0,1,1]], "divisions": [2, 1, 1], "vertices": {"7": "tip"}}),
)
.unwrap();
s.execute("geometry.datum.point", &json!({"name": "Tip", "by": {"type": "vertex", "body": "Bar", "vertex": "tip"}})).unwrap();
assert_eq!(s.model.datum("Tip").and_then(Datum::point), Some([4.0, 1.0, 1.0]));
}
#[test]
fn editing_and_deleting_datums_follow_their_partitions() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 15}})).unwrap();
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
let cut_at = |s: &Session| s.design.as_ref().unwrap().bodies[0].measure().unwrap().bbox_max[0];
assert!((cut_at(&s) - 15.0).abs() < 1e-6);
// Moving the plane cuts again; an edit of the wrong kind or to an axis is refused.
s.execute("geometry.datum.edit", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 25}})).unwrap();
assert!((cut_at(&s) - 25.0).abs() < 1e-6);
assert!(s.execute("geometry.datum.axis.edit", &json!({"name": "Mid", "by": {"type": "principal", "axis": "y"}})).is_err());
assert!(s.execute("geometry.datum.edit", &json!({"name": "Ax", "by": {"type": "offset", "plane": "xy"}})).is_err());
s.execute("geometry.datum.axis.edit", &json!({"name": "Ax", "by": {"type": "principal", "axis": "y"}})).unwrap();
assert_eq!(s.model.datum("Ax"), Some(&Datum::Axis { point: [0.0; 3], direction: [0.0, 1.0, 0.0] }));
// The edit commands take the parameters edit_params gives back.
for name in ["Mid", "Ax"] {
let (command, params) = edit_params(name, s.model.datum(name).unwrap());
s.execute(command, &params).unwrap();
}
// Deleting the plane names its partition, or deletes it too.
let e = s.execute("geometry.datum.delete", &json!({"name": "Mid"})).unwrap_err().to_string();
assert!(e.contains("partition `Half`"), "{e}");
let r = s.execute("geometry.datum.delete", &json!({"name": "Mid", "cascade": true})).unwrap();
assert_eq!(r["partitions"], json!(["Half"]));
assert!(s.model.partitions().is_empty() && s.model.datum("Mid").is_none());
assert_eq!(bodies(&s).len(), 1);
// One undo step brings both back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((s.model.partitions().len(), bodies(&s).len()), (1, 2));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_partition_that_cuts_nothing_changes_nothing() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Out", "by": {"type": "offset", "plane": "yz", "offset": 100}})).unwrap();
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
let journal = s.journal.len();
for p in [
json!({"name": "P", "datum": "Out"}),
json!({"name": "P", "datum": "Ax"}),
json!({"name": "P", "datum": "Nope"}),
json!({"name": "P", "datum": "Out", "bodies": ["Nope"]}),
json!({"name": "P", "datum": "Out", "bodies": "x"}),
json!({"name": "", "datum": "Out"}),
] {
assert!(s.execute("geometry.partition", &p).is_err(), "{p}");
}
assert!(s.model.partitions().is_empty());
assert_eq!(bodies(&s).len(), 1);
assert_eq!(s.journal.len(), journal);
let _ = std::fs::remove_dir_all(&dir);
}
}
+3 -1
View File
@@ -6,6 +6,7 @@ use fieldcraft_io::roots::Access;
use serde_json::{Value, json};
use super::req;
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const WRITE: CommandSpec = CommandSpec {
@@ -14,6 +15,7 @@ pub const WRITE: CommandSpec = CommandSpec {
params: r#"{"format": "abaqus|nastran|lsdyna", "path": "part.inp", "steps": ["Load"]} — writes the model as a solver deck (formats: fieldcraft_decks::FORMATS); `steps` (optional) writes only those steps, as a Nastran run needs (static or frequency steps, not both); LS-DYNA writes several steps as *CASE analyses (run it with CASE); fails naming every error of the model check and everything the format cannot express"#,
form: Some(super::forms::DECK),
kind: CommandKind::Session,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection],
run: write,
};
@@ -60,7 +62,7 @@ mod tests {
assert!(s.execute("deck.write", &json!({"path": other})).is_err());
assert!(s.execute("deck.write", &json!({"format": "abaqus"})).is_err());
let mut empty = Session::default();
assert!(matches!(empty.execute("deck.write", &json!({"format": "abaqus", "path": other})), Err(EngineError::Deck(_))));
assert!(matches!(empty.execute("deck.write", &json!({"format": "abaqus", "path": other})), Err(EngineError::Unavailable(_))));
assert!(!dir.join("other.inp").exists());
assert!(matches!(s.execute("deck.write", &json!({"format": "abaqus", "path": dir.to_string_lossy()})), Err(EngineError::File(_))));
+43 -11
View File
@@ -14,6 +14,7 @@ use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::{name, opt, req};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
/// The parameters other than `name`, read as a definition's JSON form.
@@ -26,13 +27,14 @@ fn fields<T: DeserializeOwned>(p: &Value, what: &str) -> Result<T> {
/// Create, edit and delete commands for one kind of definition.
macro_rules! definition_commands {
($what:literal, $ty:ty, $id:literal, $label:literal, $doc:literal, $form:expr, $delete_form:expr, $add:ident, $replace:ident, $remove:ident,
$CREATE:ident, $EDIT:ident, $DELETE:ident) => {
$CREATE:ident, $EDIT:ident, $DELETE:ident, requires: $requires:expr, exists: $exists:ident) => {
pub const $CREATE: CommandSpec = CommandSpec {
id: concat!("model.", $id, ".create"),
label: concat!("New ", $label),
params: concat!($doc, " — fails if the name is taken"),
form: Some($form),
kind: CommandKind::Model,
requires: $requires,
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
s.model.$add(n, fields::<$ty>(p, $what)?)?;
@@ -45,6 +47,7 @@ macro_rules! definition_commands {
params: concat!($doc, " — replaces the existing definition of that name"),
form: Some($form),
kind: CommandKind::Model,
requires: &[Requirement::$exists],
run: |s: &mut Session, p: &Value| {
let n = name(p)?;
s.model.$replace(n, fields::<$ty>(p, $what)?)?;
@@ -57,6 +60,7 @@ macro_rules! definition_commands {
params: r#"{"name": "…"} — refused while another definition refers to it"#,
form: Some($delete_form),
kind: CommandKind::Model,
requires: &[Requirement::$exists],
run: |s: &mut Session, p: &Value| {
s.model.$remove(name(p)?)?;
Ok(Value::Null)
@@ -78,7 +82,9 @@ definition_commands!(
remove_set,
SET_CREATE,
SET_EDIT,
SET_DELETE
SET_DELETE,
requires: &[],
exists: Set
);
definition_commands!(
@@ -94,7 +100,9 @@ definition_commands!(
remove_material,
MATERIAL_CREATE,
MATERIAL_EDIT,
MATERIAL_DELETE
MATERIAL_DELETE,
requires: &[],
exists: Material
);
/// A copy of material `name` with `change` applied, put back through the model's validation.
@@ -112,6 +120,7 @@ pub const MATERIAL_PLASTICITY: CommandSpec = CommandSpec {
params: r#"{"name": "Steel", "plastic": {"type": "bilinear", "yield_stress": 250, "hardening_modulus": 1000, "hardening": "isotropic|kinematic"} | {"type": "table", "points": [{"strain": 0, "stress": 250}, {"strain": 0.1, "stress": 300}]} | {"type": "johnson_cook", "a": 792, "b": 510, "n": 0.26, "c": 0.014, "m": 1.03, "reference_strain_rate": 1, "room_temperature": 294, "melt_temperature": 1793, "specific_heat": 4.77e8, "taylor_quinney": 0.9} | null} — von Mises plasticity of an isotropic material (null removes it); explicit dynamics uses it, the linear solver the elastic constants alone"#,
form: Some(super::forms::MATERIAL_PLASTICITY),
kind: CommandKind::Model,
requires: &[Requirement::Material],
run: |s: &mut Session, p: &Value| {
change_material(s, p, |m, p| {
m.plastic = req(p, "plastic")?;
@@ -126,6 +135,7 @@ pub const MATERIAL_DAMAGE: CommandSpec = CommandSpec {
params: r#"{"name": "Steel", "damage": {"type": "johnson_cook", "d1": 0.05, "d2": 3.44, "d3": -2.12, "d4": 0.002, "d5": 0.61} | null, "erosion": {"plastic_strain": 1.0} | null} — damage to failure and element erosion of a plastic material (each key optional; null removes it); a failed element is eroded in explicit dynamics"#,
form: Some(super::forms::MATERIAL_DAMAGE),
kind: CommandKind::Model,
requires: &[Requirement::Material],
run: |s: &mut Session, p: &Value| {
change_material(s, p, |m, p| {
// Absent leaves a field as it is; null removes it.
@@ -157,7 +167,9 @@ definition_commands!(
remove_section,
SECTION_CREATE,
SECTION_EDIT,
SECTION_DELETE
SECTION_DELETE,
requires: &[Requirement::Material, Requirement::Set],
exists: Section
);
definition_commands!(
@@ -173,7 +185,9 @@ definition_commands!(
remove_reference_point,
REFERENCE_POINT_CREATE,
REFERENCE_POINT_EDIT,
REFERENCE_POINT_DELETE
REFERENCE_POINT_DELETE,
requires: &[],
exists: ReferencePoint
);
definition_commands!(
@@ -189,7 +203,9 @@ definition_commands!(
remove_coupling,
COUPLING_CREATE,
COUPLING_EDIT,
COUPLING_DELETE
COUPLING_DELETE,
requires: &[Requirement::ReferencePoint, Requirement::Set],
exists: Coupling
);
definition_commands!(
@@ -205,7 +221,9 @@ definition_commands!(
remove_mass,
MASS_CREATE,
MASS_EDIT,
MASS_DELETE
MASS_DELETE,
requires: &[Requirement::Target],
exists: Mass
);
definition_commands!(
@@ -221,7 +239,9 @@ definition_commands!(
remove_spring,
SPRING_CREATE,
SPRING_EDIT,
SPRING_DELETE
SPRING_DELETE,
requires: &[Requirement::Target],
exists: Spring
);
definition_commands!(
@@ -237,7 +257,9 @@ definition_commands!(
remove_boundary_condition,
BOUNDARY_CONDITION_CREATE,
BOUNDARY_CONDITION_EDIT,
BOUNDARY_CONDITION_DELETE
BOUNDARY_CONDITION_DELETE,
requires: &[Requirement::Target],
exists: BoundaryCondition
);
definition_commands!(
@@ -253,7 +275,9 @@ definition_commands!(
remove_load,
LOAD_CREATE,
LOAD_EDIT,
LOAD_DELETE
LOAD_DELETE,
requires: &[],
exists: Load
);
definition_commands!(
@@ -269,7 +293,9 @@ definition_commands!(
remove_fluid_domain,
FLUID_DOMAIN_CREATE,
FLUID_DOMAIN_EDIT,
FLUID_DOMAIN_DELETE
FLUID_DOMAIN_DELETE,
requires: &[Requirement::Material],
exists: FluidDomain
);
pub const FLUID_BOUNDARY: CommandSpec = CommandSpec {
@@ -278,6 +304,7 @@ pub const FLUID_BOUNDARY: CommandSpec = CommandSpec {
params: r#"{"domain": "Flow", "at": "x_min" (a box face) | {"body": "Body1", "face": "F2:top"} (an obstacle face), "condition": {"type": "velocity", "velocity": [u, v, w], "profile": "uniform|parabolic"} | {"type": "pressure", "pressure": 0} | {"type": "wall"} | {"type": "moving_wall", "velocity": [u, v, w]} | {"type": "slip"} | {"type": "periodic"}} — sets one boundary's condition (obstacle faces take walls and moving walls)"#,
form: Some(super::forms::FLUID_BOUNDARY),
kind: CommandKind::Model,
requires: &[Requirement::FluidDomain],
run: fluid_boundary,
};
@@ -295,6 +322,7 @@ pub const STEP_CREATE: CommandSpec = CommandSpec {
params: r#"{"name": "Bend", "procedure": {"type": "static"} | {"type": "nonlinear_static", "nonlinear_geometry": true, "initial_increment": 0.1, "min_increment": 1e-5, "max_increment": 1.0 (fractions of the step), "max_increments": 100, "max_iterations": 16 (per increment), "tolerances": {"force": 1e-6, "displacement": 1e-5, "energy": 1e-10}, "line_search": false, "load_path": [[0, 0], [0.5, 1], [1, 0]] (optional: the load factor against the step fraction, piecewise linear from [0, 0] to fraction 1; increments end at its points)} (loads and prescribed displacements are the load factor times their values; it ramps from 0 to 1 without a load path) | {"type": "frequency", "modes": 10, "min_hz": 0, "max_hz": 500} | {"type": "fluid", "domain": "Flow", "end_time": 1.0 | "steps": 1000, "time_step": (default: chosen for Mach 0.087 and τ ≤ 1), "frames": 10, "magic": 0.1875 (the two-relaxation-time Λ)} | {"type": "explicit_dynamic", "end_time": 0.001, "dt_scale": 0.9, "max_increments": 10000000, "output_interval", "history_interval", "history_nodes": "set", "initial_velocities": [{"set", "velocity": [vx, vy, vz]}], "rigid_walls": [{"set", "point", "normal", "friction": {"static": 0.3, "kinetic": 0.2, "decay": 10} (Coulomb; default frictionless)}], "hourglass": {"type": "viscous|stiffness", "coefficient": 0.1}, "bulk_viscosity": {"linear": 0.06, "quadratic": 1.5}, "mass_scaling": {"target_increment": 1e-6, "set": "…" (optional, default every element)} (opt-in: elements below the target increment get the density that reaches it; the added mass is reported)}, "output": ["displacement", "reaction_force", "stress", "strain"] (default by procedure), "boundary_conditions": [names], "loads": [names] (active in this step; nothing carries over between steps), "before": "step" (default: last)}"#,
form: Some(super::forms::STEP_CREATE),
kind: CommandKind::Model,
requires: &[],
run: step_create,
};
@@ -304,6 +332,7 @@ pub const STEP_EDIT: CommandSpec = CommandSpec {
params: r#"{"name": "Bend", "procedure", "output", "boundary_conditions", "loads"} — as model.step.create; what is left out keeps its value"#,
form: Some(super::forms::STEP_EDIT),
kind: CommandKind::Model,
requires: &[Requirement::Step],
run: step_edit,
};
@@ -313,6 +342,7 @@ pub const STEP_DELETE: CommandSpec = CommandSpec {
params: r#"{"name": "Bend"}"#,
form: Some(super::forms::STEP_DELETE),
kind: CommandKind::Model,
requires: &[Requirement::Step],
run: |s, p| s.model.remove_step(name(p)?).map(|_| Value::Null).map_err(Into::into),
};
@@ -322,6 +352,7 @@ pub const STEP_ACTIVATE: CommandSpec = CommandSpec {
params: r#"{"step": "Bend", "boundary_conditions": [names], "loads": [names], "active": true} — switches the listed items on (or off with false) in that step only"#,
form: Some(super::forms::STEP_ACTIVATE),
kind: CommandKind::Model,
requires: &[Requirement::Step],
run: step_activate,
};
@@ -331,6 +362,7 @@ pub const ACTIVITY: CommandSpec = CommandSpec {
params: "{}",
form: Some(&[]),
kind: CommandKind::Model,
requires: &[],
run: |s, _| Ok(activity(&s.model)),
};
+133
View File
@@ -0,0 +1,133 @@
//! Crash reports and bug report drafts (docs/crash-reports.md): list and read the reports the
//! desktop app wrote, draft a bug report, and (with `FIELDCRAFT_CRASH_TEST=1`) crash on purpose
//! to check that reporting works.
use std::path::PathBuf;
use fieldcraft_io::roots::Access;
use serde_json::{Value, json};
use super::{file_param, opt, req};
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, bug_report, crash};
pub const CRASH_REPORTS: CommandSpec = CommandSpec {
id: "diagnostics.crash_reports",
label: "Crash Reports",
params: r#"{"limit"?: 20, "dir"?: "…"} — the crash reports the desktop app wrote on this computer, newest first: id, kind (command_panic, recovered_panic, panic, unclean_exit), time, message, command, count, version, path and whether it can be replayed (default folder: FIELDCRAFT_CRASH_DIR, a temporary folder in runs driven by automation, else the per-user data folder)"#,
form: Some(super::forms::CRASH_REPORTS),
kind: CommandKind::Session,
requires: &[],
run: crash_reports,
};
pub const CRASH_REPORT: CommandSpec = CommandSpec {
id: "diagnostics.crash_report",
label: "Crash Report",
params: r#"{"id": "20261014-101500-…", "dir"?: "…"} — one crash report: what happened, where, the backtrace, the command and recent commands, and the paths of its model, replay and log files"#,
form: Some(super::forms::CRASH_REPORT),
kind: CommandKind::Session,
requires: &[],
run: crash_report,
};
pub const BUG_REPORT: CommandSpec = CommandSpec {
id: "diagnostics.bug_report",
label: "Report a Bug",
params: r#"{"title"?: "…", "observed"?: "what happened", "crash"?: "<crash report id>", "share_session"?: false, "include_model"?: false} — drafts a GitHub bug report: the issue link (the bug form filled with the version, the OS, what happened and, for a crash, where), and the files to attach. Only with share_session does it carry the model's commands, and only with include_model as well the model file. Nothing is sent: the desktop app's Help › Report a Bug shows the draft and opens the link when the user asks"#,
form: Some(super::forms::BUG_REPORT),
kind: CommandKind::Session,
requires: &[],
run: bug_report_draft,
};
pub const CRASH_TEST: CommandSpec = CommandSpec {
id: "diagnostics.crash_test",
label: "Crash Test",
params: r#"{"mode": "panic|recovered|abort"} — crashes on purpose to check that crash reports work (only with FIELDCRAFT_CRASH_TEST=1): panic, an internal error in this command; recovered, one caught inside it; abort, the app ends at once (reported at its next start)"#,
form: Some(super::forms::CRASH_TEST),
kind: CommandKind::Session,
requires: &[],
run: crash_test,
};
fn crash_dir(s: &Session, p: &Value) -> Result<PathBuf> {
if p.get("dir").is_some() {
return Ok(PathBuf::from(file_param(s, p, "dir", Access::Read)?));
}
crash::default_dir().ok_or_else(|| EngineError::Params("no crash folder: set FIELDCRAFT_CRASH_DIR or give `dir`".into()))
}
fn crash_reports(s: &mut Session, p: &Value) -> Result<Value> {
let dir = crash_dir(s, p)?;
let limit = opt::<usize>(p, "limit")?.unwrap_or(crash::MAX_REPORTS);
let mut reports = crash::list(&dir);
reports.truncate(limit);
Ok(json!({"dir": dir.to_string_lossy(), "reports": reports}))
}
fn crash_report(s: &mut Session, p: &Value) -> Result<Value> {
let dir = crash_dir(s, p)?;
let id = req::<String>(p, "id")?;
crash::read(&dir, &id).map_err(EngineError::Params)
}
/// The draft input for `p` from the session: its commands and model (when shared), or a crash
/// report's replay and model.
pub fn bug_report_input(s: &Session, p: &Value) -> Result<bug_report::Input> {
let share = opt::<bool>(p, "share_session")?.unwrap_or(false);
let include_model = opt::<bool>(p, "include_model")?.unwrap_or(false);
let mut input = bug_report::Input {
title: opt::<String>(p, "title")?.unwrap_or_default(),
observed: opt::<String>(p, "observed")?.unwrap_or_default(),
share_session: share,
include_model,
..Default::default()
};
match opt::<String>(p, "crash")? {
Some(id) => {
let report = crash::read(&crash_dir(s, p)?, &id).map_err(EngineError::Params)?;
if share {
let read = |k: &str| {
report
.get(k)
.and_then(Value::as_str)
.and_then(|f| fieldcraft_io::fs::read_capped(std::path::Path::new(f), crash::MAX_MODEL_BYTES as u64).ok())
};
let replay: Value = read("replay_path").and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(Value::Null);
input.commands = replay.get("commands").and_then(Value::as_array).cloned().unwrap_or_default();
input.model = if include_model { read("model_path") } else { None };
}
input.crash = Some(report);
}
None if share => {
input.commands = s.journal.iter().map(|(command, params)| json!({"command": command, "params": params})).collect();
input.model = if include_model { Some(s.file_bytes(None)?) } else { None };
}
None => {}
}
Ok(input)
}
fn bug_report_draft(s: &mut Session, p: &Value) -> Result<Value> {
let input = bug_report_input(s, p)?;
Ok(bug_report::draft(&input, &crash::Build::current().version_line()).to_json())
}
// The one deliberate panic and abort: they prove that crash reports work, and run only when
// asked for with FIELDCRAFT_CRASH_TEST=1.
#[allow(clippy::panic)]
fn crash_test(_: &mut Session, p: &Value) -> Result<Value> {
let mode = req::<String>(p, "mode")?;
if std::env::var_os("FIELDCRAFT_CRASH_TEST").is_none_or(|v| v != "1") {
return Err(EngineError::Params("the crash test runs only with FIELDCRAFT_CRASH_TEST=1".into()));
}
match mode.as_str() {
"panic" => std::panic::panic_any(String::from("crash test: an internal error in a command")),
"recovered" => {
let caught = std::panic::catch_unwind(|| std::panic::panic_any(String::from("crash test: an internal error caught inside a command")));
Ok(json!({"caught": caught.is_err()}))
}
"abort" => std::process::abort(),
_ => Err(EngineError::invalid("mode", "must be panic, recovered or abort")),
}
}
+2
View File
@@ -38,6 +38,7 @@ pub const UNDO: CommandSpec = CommandSpec {
params: r#"{"count"?: 1} — takes back the last command that changed the model (it leaves the journal and can be redone); `count` takes back that many, as far as the history reaches"#,
form: Some(super::forms::COUNT),
kind: CommandKind::Session,
requires: &[],
run: |s, p| repeat(s, p, Session::undo),
};
@@ -47,6 +48,7 @@ pub const REDO: CommandSpec = CommandSpec {
params: r#"{"count"?: 1} — runs the last undone command's change again; `count` redoes that many, as far as there are undone commands"#,
form: Some(super::forms::COUNT),
kind: CommandKind::Session,
requires: &[],
run: |s, p| repeat(s, p, Session::redo),
};
+57 -10
View File
@@ -25,6 +25,7 @@ pub const OPEN: CommandSpec = CommandSpec {
params: r#"{"path": "bracket.fieldcraft"} — opens the model, its mesh and its journal, and opens its design and imported meshes again from their files (one that is missing or changed is listed in `warnings`; the model still opens); unsaved changes of the current model are discarded and the undo history starts empty"#,
form: Some(super::forms::FILE_OPEN),
kind: CommandKind::Session,
requires: &[],
run: open,
};
@@ -34,6 +35,7 @@ pub const SAVE: CommandSpec = CommandSpec {
params: r#"{"path"?: "bracket.fieldcraft"} — saves to `path`, else to the file the model was opened from or last saved to; written atomically, the previous version kept as `<file>.bak`"#,
form: Some(super::forms::FILE_SAVE),
kind: CommandKind::Session,
requires: &[],
run: save,
};
@@ -43,15 +45,17 @@ pub const SAVE_AS: CommandSpec = CommandSpec {
params: r#"{"path": "bracket.fieldcraft"} — saves to a new file, which becomes the model's file"#,
form: Some(super::forms::FILE_SAVE_AS),
kind: CommandKind::Session,
requires: &[],
run: save_as,
};
pub const RECOVERY_LIST: CommandSpec = CommandSpec {
id: "file.recovery.list",
label: "Recoverable Models",
params: r#"{"dir"?: "…"} — models autosaved by apps that crashed or closed with unsaved changes, newest first (default folder: FIELDCRAFT_RECOVERY_DIR or the per-user data folder)"#,
params: r#"{"dir"?: "…"} — models autosaved by apps that crashed or closed with unsaved changes, newest first, each with its id, path, saved_at, age (seconds) and node and element counts (default folder: FIELDCRAFT_RECOVERY_DIR, a temporary folder in runs driven by automation, else the per-user data folder)"#,
form: Some(super::forms::RECOVERY_LIST),
kind: CommandKind::Session,
requires: &[],
run: recovery_list,
};
@@ -61,6 +65,7 @@ pub const RECOVER: CommandSpec = CommandSpec {
params: r#"{"id": "…", "dir"?: "…"} — opens an autosaved model (an id from file.recovery.list) with its original file path, as unsaved changes; the autosave stays until file.recovery.discard"#,
form: Some(super::forms::RECOVER),
kind: CommandKind::Session,
requires: &[],
run: recover,
};
@@ -70,15 +75,17 @@ pub const RECOVERY_DISCARD: CommandSpec = CommandSpec {
params: r#"{"id": "…"} or {"all": true}; "dir"?: "…" — deletes autosaves of apps that are no longer running"#,
form: Some(super::forms::RECOVERY_DISCARD),
kind: CommandKind::Session,
requires: &[],
run: recovery_discard,
};
pub const SAMPLE: CommandSpec = CommandSpec {
id: "file.sample",
label: "Open Sample",
params: r#"{"name": "parts|cantilever|impact"} — opens a sample model (fieldcraft_engine::sample) in place of the current one, unsaved changes discarded; `cantilever` and `impact` are ready to solve (solve.run)"#,
params: r#"{"name": "cantilever"} — opens a sample model (fieldcraft_engine::sample; the list is in docs/examples.md) in place of the current one, unsaved changes discarded; every sample but `parts` is ready to solve (solve.run)"#,
form: Some(super::forms::SAMPLE),
kind: CommandKind::Session,
requires: &[],
run: open_sample,
};
@@ -87,9 +94,18 @@ fn open_sample(s: &mut Session, p: &Value) -> Result<Value> {
let names = || crate::sample::SAMPLES.iter().map(|x| x.name).collect::<Vec<_>>().join(", ");
let sample = crate::sample::find(name).ok_or_else(|| EngineError::Params(format!("no sample `{name}` (samples: {})", names())))?;
let mut opened = Session::default();
opened.run_script(&(sample.script)())?;
if let Some(recipe) = sample.design {
opened.design = Some(Arc::new(open_design(&fieldcraft_geometry::script_design(recipe)?)?));
}
if let Some(prepare) = sample.prepare {
opened.run_script(&prepare())?;
}
let bodies = opened.design.as_ref().map_or(&[][..], |d| d.bodies.as_slice());
let script = (sample.script)(bodies);
opened.run_script(&script)?;
// A sample just opened has nothing to save: it opens again the same way.
opened.saved_revision = Some(opened.revision);
opened.saved_view = opened.view.clone();
s.replace_with(opened);
let mut reply = summary(s, &[]);
reply["sample"] = json!(sample.name);
@@ -175,7 +191,7 @@ impl Session {
design: self.sources.design.as_ref().map(stored).transpose()?,
meshes: self.sources.meshes.iter().map(stored).collect::<fieldcraft_io::Result<_>>()?,
};
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal)?)
Ok(fieldcraft_io::write(&self.model, &geometry, &self.journal, &self.view)?)
}
/// A session holding what a file holds, its geometry opened again from the paths it names
@@ -187,7 +203,16 @@ impl Session {
let mut design: Option<Arc<Design>> = None;
if let Some(stored) = &file.geometry.design {
let (opened, source) = reopen("design", stored, base, roots, MAX_DESIGN_BYTES as u64, open_design, &mut warnings);
design = opened.map(Arc::new);
design = opened.and_then(|d| match super::datum::partitioned(&d, &file.model) {
Ok(cut) => Some(Arc::new(cut)),
Err(e) => {
warnings.push(format!("the design's partitions could not be applied ({e}); the model opens without the design"));
None
}
});
if let Some(d) = &design {
warnings.extend(d.errors.iter().filter(|e| e.feature.starts_with("partition ")).map(|e| format!("{}: {}", e.feature, e.message)));
}
sources.design = Some(source);
}
let mut surfaces = Vec::new();
@@ -196,18 +221,30 @@ impl Session {
surfaces.extend(opened.into_iter().flatten().map(Arc::new));
sources.meshes.push(source);
}
let session =
Session { model: file.model, design, surfaces, sources, journal: file.journal, revision: next_revision(), ..Session::default() };
let session = Session {
model: file.model,
design,
surfaces,
sources,
journal: file.journal,
revision: next_revision(),
saved_view: file.view.clone(),
view: file.view,
..Session::default()
};
(session, warnings)
}
/// Replace this session with `opened`, keeping its undo memory limit, its work caps and its
/// file access; the history starts empty.
/// file access (and where its commands come from); the history starts empty.
fn replace_with(&mut self, mut opened: Session) {
opened.history = std::mem::take(&mut self.history);
opened.limits = self.limits;
opened.file_access = std::mem::take(&mut self.file_access);
opened.crash_journal = self.crash_journal;
opened.origin = self.origin;
opened.clear_history();
opened.mark_opened();
*self = opened;
}
}
@@ -283,8 +320,15 @@ fn recovery_dir(s: &Session, p: &Value, access: Access) -> Result<PathBuf> {
}
fn recovery_list(s: &mut Session, p: &Value) -> Result<Value> {
let entries = fieldcraft_io::recovery::orphans(&recovery_dir(s, p, Access::Read)?);
serde_json::to_value(entries).map_err(|e| EngineError::Params(e.to_string()))
let mut listed = Vec::new();
for e in fieldcraft_io::recovery::orphans(&recovery_dir(s, p, Access::Read)?) {
let mut v = serde_json::to_value(&e).map_err(|e| EngineError::Params(e.to_string()))?;
if let Some(o) = v.as_object_mut() {
o.insert("age".into(), json!(e.age()));
}
listed.push(v);
}
Ok(Value::Array(listed))
}
fn recover(s: &mut Session, p: &Value) -> Result<Value> {
@@ -400,6 +444,9 @@ mod tests {
refused(s.execute("file.recovery.discard", &json!({"all": true, "dir": input})));
s.execute("geometry.open", &json!({"path": input.join("plate.solidcraft")})).unwrap();
defined(&mut s);
// A section, so deck.write has all it needs and reaches its path.
s.execute("model.set.create", &json!({"name": "all", "elements": [1]})).unwrap();
s.execute("model.section.create", &json!({"name": "solid", "set": "all", "material": "Steel", "kind": {"type": "solid"}})).unwrap();
// Writes go to the write root only: not the read root, not elsewhere.
refused(s.execute("file.save_as", &json!({"path": input.join("m.fieldcraft")})));
refused(s.execute("file.save_as", &json!({"path": outside.join("m.fieldcraft")})));
File diff suppressed because it is too large. Load diff
+86 -6
View File
@@ -1,28 +1,35 @@
use crate::schema::ProblemKind;
use std::collections::BTreeSet;
use std::sync::Arc;
use fieldcraft_geometry::tagged_mesh;
use fieldcraft_geometry::{MAX_DESIGN_BYTES, Shape, SurfaceMesh, open_design};
use fieldcraft_geometry::{Design, MAX_DESIGN_BYTES, Shape, SurfaceMesh, open_design};
use fieldcraft_io::SourceFile;
use fieldcraft_io::roots::Access;
use fieldcraft_model::Model;
use fieldcraft_model::geometry::{Entity, GeometryRef};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const OPEN: CommandSpec = CommandSpec {
id: "geometry.open",
label: "Open Design",
params: r#"{"path": "part.solidcraft"} — rebuilds the SolidCraft design and makes its bodies the geometry; opening it again after an edit picks up the change"#,
params: r#"{"path": "part.solidcraft", "model"?: "keep"} — rebuilds the SolidCraft design and makes its bodies the geometry. `model`: "keep" (default) keeps the mesh and every definition, so opening the same design again after an edit picks up the change and sets follow their persistent face names; "new" starts a new model with the design (no mesh, sets, materials, sections, BCs, loads or steps; the unit system stays; the model is untitled until saved, and undo restores the previous file). The reply's `related` is false when the model (before the open) refers to bodies (mesh tags, set geometry) and the design has none of them, and `stale` lists what no longer resolves: `mesh_bodies` (bodies the mesh is tagged with that the design lacks) `sets` (sets naming a body or face it lacks) and `seeds` (edge seeds on edges it lacks). One undo step"#,
form: Some(super::forms::OPEN_DESIGN),
kind: CommandKind::Model,
requires: &[],
run: open,
};
pub const BODIES: CommandSpec = CommandSpec {
id: "geometry.bodies",
label: "Bodies",
params: "{} — the open design's bodies: measures and persistent face names (by face index)",
params: "{} — the open design's bodies: measures, persistent face names (by face index) and edges (persistent name `<face>|<face>`, `~k` when several separate the same faces, and length)",
form: Some(&[]),
kind: CommandKind::Model,
requires: &[], // No design is an answer too: no bodies.
run: bodies,
};
@@ -32,6 +39,7 @@ pub const TESSELLATE: CommandSpec = CommandSpec {
params: r#"{"body": "Body1", "tolerance": 0.05} — triangulates the body's boundary within the chordal tolerance (mm); reports triangles per face"#,
form: Some(super::forms::TESSELLATE),
kind: CommandKind::Model,
requires: &[Requirement::Design],
run: tessellate,
};
@@ -41,29 +49,100 @@ pub const IMPORT_MESH: CommandSpec = CommandSpec {
params: r#"{"path": "part.3mf"} — adds each build item of a 3MF package as a surface; triangles keep their B-rep face tags (docs/formats/tagged-mesh.md)"#,
form: Some(super::forms::IMPORT_MESH),
kind: CommandKind::Model,
requires: &[],
run: import_mesh,
};
fn open(s: &mut Session, p: &Value) -> Result<Value> {
let new_model = match p.get("model") {
None | Some(Value::Null) => false,
Some(v) => match v.as_str() {
Some("keep") => false,
Some("new") => true,
_ => return Err(EngineError::Params(r#"`model` must be "keep" or "new""#.into())),
},
};
let path = super::file_param(s, p, "path", Access::Read)?;
let bytes = super::file::read_file(&path, MAX_DESIGN_BYTES as u64)?;
let source = SourceFile::of(super::file::absolute(&path), &bytes)?;
let design = open_design(&bytes)?;
let opened = open_design(&bytes)?;
// The model's partitions cut the design again (a new model has none).
let design = if new_model { opened } else { super::datum::partitioned(&opened, &s.model)? };
let mut fit = fit(s, &design);
if new_model {
let mut model = Model::default();
model.set_units(s.model.units());
s.model = model;
s.surfaces.clear();
s.sources.meshes.clear();
s.results_view = None;
// A new model is untitled: saving asks for a file instead of overwriting the old model's
// (undo brings the old file back with the old model).
s.set_document(Default::default());
fit.mesh_bodies.clear();
fit.sets.clear();
fit.seeds.clear();
}
let out = json!({
"name": design.name,
"bodies": design.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
"errors": design.errors.iter().map(|e| json!({"feature": e.feature, "message": e.message})).collect::<Vec<_>>(),
"model": if new_model { "new" } else { "kept" },
"related": fit.related,
"stale": {"mesh_bodies": fit.mesh_bodies, "sets": fit.sets, "seeds": fit.seeds},
});
// Another design file (or a new model) is another document; the same file opened again after
// an edit is the same one.
if new_model || s.sources.design.as_ref().is_none_or(|d| d.path() != source.path()) {
s.mark_opened();
}
s.design = Some(Arc::new(design));
s.sources.design = Some(source);
Ok(out)
}
/// How the model's geometry references fit a design about to become the geometry.
struct Fit {
/// Whether the design (or an imported surface) has a body the model refers to, or the model
/// refers to none: `false` means the model is of another part.
related: bool,
/// Bodies the mesh is tagged with that neither the design nor a surface has.
mesh_bodies: Vec<String>,
/// Sets naming a body or a face that is not there.
sets: Vec<String>,
/// Edge seeds on an edge the design lacks.
seeds: Vec<String>,
}
fn fit(s: &Session, design: &Design) -> Fit {
let has = |body: &str| design.body(body).is_some() || s.surfaces.iter().any(|t| t.name == body);
let resolves = |r: &GeometryRef| match (&r.entity, design.body(&r.body)) {
(Entity::Face(face), Some(b)) => b.faces().iter().any(|f| &f.name == face),
_ => has(&r.body),
};
let tagged: BTreeSet<&str> = s.model.classification().entities().iter().map(|r| r.body.as_str()).collect();
let mut referenced = tagged.clone();
referenced.extend(s.model.sets().values().flat_map(|set| set.geometry.iter().map(|r| r.body.as_str())));
Fit {
related: referenced.is_empty() || referenced.iter().any(|b| has(b)),
mesh_bodies: tagged.into_iter().filter(|b| !has(b)).map(str::to_string).collect(),
sets: s.model.sets().iter().filter(|(_, set)| !set.geometry.iter().all(resolves)).map(|(n, _)| n.clone()).collect(),
seeds: s
.model
.seeds()
.iter()
.filter(|seed| super::seeds::seeded_edges(design, &seed.edge).map_or(true, |e| e.is_empty()))
.map(|seed| seed.edge.to_string())
.collect(),
}
}
fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
let Some(design) = &s.design else { return Ok(json!([])) };
let mut out = Vec::with_capacity(design.bodies.len());
for b in &design.bodies {
let m = b.measure()?;
let edges: Vec<Value> = b.edges()?.iter().map(|e| json!({"name": e.name, "length": e.length()})).collect();
out.push(json!({
"name": b.name,
"volume": m.volume,
@@ -71,20 +150,21 @@ fn bodies(s: &mut Session, _: &Value) -> Result<Value> {
"centroid": m.centroid,
"bbox": [m.bbox_min, m.bbox_max],
"faces": b.faces().iter().map(|f| json!({"name": f.name, "exact": f.exact})).collect::<Vec<_>>(),
"edges": edges,
}));
}
Ok(Value::Array(out))
}
fn body<'a>(s: &'a Session, p: &Value) -> Result<&'a Shape> {
let name = p.get("body").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`body` must be a body name".into()))?;
let name = p.get("body").and_then(Value::as_str).ok_or_else(|| EngineError::param("body", ProblemKind::NotAName))?;
s.design.as_deref().and_then(|d| d.body(name)).ok_or_else(|| EngineError::Params(format!("no body `{name}` (open a design first)")))
}
/// The body named by `body`, tessellated within `tolerance`.
pub(crate) fn body_mesh<'a>(s: &'a Session, p: &Value) -> Result<(&'a Shape, SurfaceMesh)> {
let shape = body(s, p)?;
let tolerance = p.get("tolerance").and_then(Value::as_f64).ok_or_else(|| EngineError::Params("`tolerance` must be a number (mm)".into()))?;
let tolerance = p.get("tolerance").and_then(Value::as_f64).ok_or_else(|| EngineError::param("tolerance", ProblemKind::NotANumber))?;
Ok((shape, shape.tessellate(tolerance)?))
}
+119 -72
View File
@@ -1,5 +1,6 @@
//! Structured hexahedral meshing of the open design's bodies or of imported surfaces.
use crate::schema::ProblemKind;
use std::borrow::Cow;
use fieldcraft_geometry::{FaceSurface, Shape, SurfaceMesh};
@@ -9,14 +10,16 @@ use fieldcraft_mesh::surface::BoundarySurface;
use fieldcraft_model::{GeometryRef, Model};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const HEX_GENERATE: CommandSpec = CommandSpec {
id: "mesh.hex.generate",
label: "Generate Hex Mesh",
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the mesh with structured hexahedra: multi-level sweeps along a direction or around an axis, one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
label: "Hex Mesh",
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "method": "auto" (default) | "swept" (any sweep) | "extrude" | "sweep" | "revolve" | "mapped", "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal)} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with structured hexahedra: multi-level sweeps along a direction or around an axis (their cross-section cut into mappable blocks automatically: O-grids round holes, triangle primitives, four-sided blocks; nothing is added to the model), one-to-one sweeps through linking faces, or mapped blocks. Boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name; `weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate), so sets by geometry resolve. Edge seeds (mesh.seed.edge) set the counts and spacing of their edges: exact seeds are held, and seeds that cannot all hold (opposite sides of a mapped face, the layers between two levels) are an error naming them. Reports per body the method, counts and quality; a body no structured method fits is an error that says why"#,
form: Some(super::forms::HEX_GENERATE),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: hex_generate,
};
@@ -33,9 +36,12 @@ const DEFAULT_RELATIVE_TOLERANCE: f64 = 1e-3;
pub(super) struct Input<'a> {
pub(super) name: String,
pub(super) mesh: Cow<'a, SurfaceMesh>,
surfaces: Vec<Option<Surface>>,
pub(super) surfaces: Vec<Option<Surface>>,
pub(super) face_names: Vec<String>,
pub(super) diagonal: f64,
/// The design's edge seeds ([`super::seeds::edge_seeds`]); the mesher applies those on its
/// edges.
pub(super) seeds: Vec<fieldcraft_mesh::seeds::EdgeSeed>,
}
fn analytic(s: FaceSurface) -> Surface {
@@ -51,11 +57,7 @@ fn analytic(s: FaceSurface) -> Surface {
pub(super) fn number(p: &Value, key: &str) -> Result<Option<f64>> {
match p.get(key) {
None => Ok(None),
Some(v) => v
.as_f64()
.filter(|x| x.is_finite() && *x > 0.0)
.map(Some)
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a positive number (mm)"))),
Some(v) => v.as_f64().filter(|x| x.is_finite() && *x > 0.0).map(Some).ok_or_else(|| EngineError::param(key, ProblemKind::NotPositive)),
}
}
@@ -63,7 +65,7 @@ fn diagonal(lo: [f64; 3], hi: [f64; 3]) -> f64 {
(0..3).map(|i| (hi[i] - lo[i]).powi(2)).sum::<f64>().sqrt()
}
fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>> {
pub(super) fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>> {
let diag = shape.size()?;
let tol = tolerance.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * diag);
if tol < MIN_RELATIVE_TOLERANCE * diag {
@@ -71,26 +73,33 @@ fn shape_input(shape: &Shape, tolerance: Option<f64>) -> Result<Input<'static>>
}
let surfaces = shape.face_surfaces()?.into_iter().map(|f| f.map(analytic)).collect();
let face_names = shape.faces().iter().map(|f| f.name.clone()).collect();
Ok(Input { name: shape.name.clone(), mesh: Cow::Owned(shape.tessellate(tol)?), surfaces, face_names, diagonal: diag })
Ok(Input { name: shape.name.clone(), mesh: Cow::Owned(shape.tessellate(tol)?), surfaces, face_names, diagonal: diag, seeds: Vec::new() })
}
/// The imported surface `surface` names, with the body name its mesh is tagged with.
pub(super) fn surface<'a>(s: &'a Session, p: &Value) -> Result<(String, &'a fieldcraft_geometry::tagged_mesh::TaggedSurface)> {
let n = s.surfaces.len();
let index = p.get("surface").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).filter(|&i| i < n);
let index = index.ok_or_else(|| EngineError::Params(format!("`surface` must be the index of an imported surface (there are {n})")))?;
let t = s.surfaces.get(index).ok_or_else(|| EngineError::Params("no such surface".into()))?;
let name = if t.name.trim().is_empty() { format!("Surface{index}") } else { t.name.clone() };
Ok((name, t))
}
pub(super) fn inputs<'a>(s: &'a Session, p: &Value) -> Result<Vec<Input<'a>>> {
let tolerance = number(p, "tolerance")?;
match (p.get("body"), p.get("surface")) {
(Some(b), None) => {
let name = b.as_str().ok_or_else(|| EngineError::Params("`body` must be a body name".into()))?;
let name = b.as_str().ok_or_else(|| EngineError::param("body", ProblemKind::NotAName))?;
let shape = s
.design
.as_deref()
.and_then(|d| d.body(name))
.ok_or_else(|| EngineError::Params(format!("no body `{name}` (open a design first)")))?;
Ok(vec![shape_input(shape, tolerance)?])
Ok(vec![Input { seeds: super::seeds::edge_seeds(s)?, ..shape_input(shape, tolerance)? }])
}
(None, Some(i)) => {
let n = s.surfaces.len();
let index = i.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < n);
let index = index.ok_or_else(|| EngineError::Params(format!("`surface` must be the index of an imported surface (there are {n})")))?;
let t = s.surfaces.get(index).ok_or_else(|| EngineError::Params("no such surface".into()))?;
(None, Some(_)) => {
let (name, t) = surface(s, p)?;
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for q in &t.mesh.positions {
for k in 0..3 {
@@ -98,17 +107,17 @@ pub(super) fn inputs<'a>(s: &'a Session, p: &Value) -> Result<Vec<Input<'a>>> {
hi[k] = hi[k].max(q[k]);
}
}
let name = if t.name.trim().is_empty() { format!("Surface{index}") } else { t.name.clone() };
// Faces named by index, as mesh.tet.generate names them.
let face_names = (0..t.faces).map(|f| f.to_string()).collect();
Ok(vec![Input { name, mesh: Cow::Borrowed(&t.mesh), surfaces: Vec::new(), face_names, diagonal: diagonal(lo, hi) }])
Ok(vec![Input { name, mesh: Cow::Borrowed(&t.mesh), surfaces: Vec::new(), face_names, diagonal: diagonal(lo, hi), seeds: Vec::new() }])
}
(None, None) => {
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first, or give `surface`".into()))?;
if design.bodies.is_empty() || design.bodies.len() > MAX_BODIES {
return Err(EngineError::Params(format!("the design has {} bodies; meshing takes 1 to {MAX_BODIES}", design.bodies.len())));
}
design.bodies.iter().map(|b| shape_input(b, tolerance)).collect()
let seeds = super::seeds::edge_seeds(s)?;
design.bodies.iter().map(|b| Ok(Input { seeds: seeds.clone(), ..shape_input(b, tolerance)? })).collect()
}
_ => Err(EngineError::Params("give `body` or `surface`, not both".into())),
}
@@ -120,6 +129,7 @@ pub const HEX_SWEEP: CommandSpec = CommandSpec {
params: r#"the parameters of mesh.hex.generate, with "method": "swept" (default: extrude, sweep or revolve, whichever fits first) | "extrude" | "sweep" | "revolve" — mesh.hex.generate limited to the sweeping methods"#,
form: Some(super::forms::HEX_SWEEP),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: hex_sweep,
};
@@ -129,33 +139,35 @@ pub const HEX_MAPPED: CommandSpec = CommandSpec {
params: r#"the parameters of mesh.hex.generate without "method" — mesh.hex.generate with the mapped method: a six-sided block (six faces of four edges, three edges at each of eight corners)"#,
form: Some(super::forms::HEX_MAPPED),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: hex_mapped,
};
pub const HEX_BLOCKS: CommandSpec = CommandSpec {
id: "mesh.hex.blocks",
label: "Block Hex Mesh",
params: r#"{"bodies": ["Cell1", "Cell2"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of that diagonal)} — replaces the mesh with one conforming all-hex mesh of a part partitioned into cells (bodies that meet face to face, such as the pieces of solid.split_body in SolidCraft): every cell a mapped block (six four-sided faces; faces that meet smoothly, such as the two halves of a hole, count as one), division counts assigned over all cells together, each shared face meshed once and its nodes merged, radial lines graded off holes and fillets. Elements are tagged with their cell's body and boundary faces with its B-rep faces (`weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate). Reports the cells, the shared faces, counts and quality; a cell that is not a block, or cells that touch without sharing whole faces, is an error that says which"#,
params: r#"{"bodies": ["Cell1", "Cell2"] (default: every body of the open design), "size": 2.0 (element size, mm; default 1/25 of the bounding-box diagonal of all of them), "order": 1 (hex8) or 2 (hex20, mid-edge nodes on the geometry), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of that diagonal)} — replaces the cells' meshes (as mesh.tet.generate; other bodies keep theirs) with one conforming all-hex mesh of a part partitioned into cells (bodies that meet face to face, such as the pieces of solid.split_body in SolidCraft): every cell a mapped block (six four-sided faces; faces that meet smoothly, such as the two halves of a hole, count as one), division counts assigned over all cells together, each shared face meshed once and its nodes merged, radial lines graded off holes and fillets. Elements are tagged with their cell's body and boundary faces with its B-rep faces (`weld`, `weld_distance` and `feature_angle` as in mesh.tet.generate). Reports the cells, the shared faces, counts and quality; a cell that is not a block, or cells that touch without sharing whole faces, is an error that says which"#,
form: Some(super::forms::HEX_BLOCKS),
kind: CommandKind::Model,
requires: &[Requirement::Design],
run: hex_blocks,
};
fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
pub(super) fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
let size = number(p, "size")?;
let quadratic = order(p)?;
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
let shapes: Vec<&Shape> = match p.get("bodies") {
None => design.bodies.iter().collect(),
Some(v) => {
let names = v.as_array().ok_or_else(|| EngineError::Params("`bodies` must be a list of body names".into()))?;
let names = v.as_array().ok_or_else(|| EngineError::param("bodies", ProblemKind::NotNames))?;
// Bounded before the duplicate check, which is quadratic in the list.
if names.len() > MAX_CELLS {
return Err(EngineError::Params(format!("`bodies` lists {} bodies; at most {MAX_CELLS} are meshed together", names.len())));
}
let mut out: Vec<&Shape> = Vec::with_capacity(names.len());
for n in names {
let name = n.as_str().ok_or_else(|| EngineError::Params("`bodies` must be a list of body names".into()))?;
let name = n.as_str().ok_or_else(|| EngineError::param("bodies", ProblemKind::NotNames))?;
let shape = design.body(name).ok_or_else(|| EngineError::Params(format!("no body `{name}`")))?;
if out.iter().any(|b| b.name == shape.name) {
return Err(EngineError::Params(format!("body `{name}` is listed twice")));
@@ -205,14 +217,17 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
quadratic,
chordal_tolerance: tolerance,
max_elements: fieldcraft_model::MAX_ELEMENTS / 8,
seeds: super::seeds::edge_seeds(s)?,
..HexOptions::default()
};
let cm = hex_mesh_cells(&cells, &UniformSize(h), &options).map_err(|e| EngineError::Params(e.to_string()))?;
let m = &cm.mesh;
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
let mut model = s.model.without_mesh();
// Replace the cells' meshes (replace.rs); other bodies and the definitions stay.
let model = &mut s.model;
let cleared = super::replace::clear(model, inputs.iter().map(|b| b.name.as_str()));
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
for (i, xyz) in m.nodes.iter().enumerate() {
model.set_node(label(i)?, *xyz)?;
model.set_node(first_node + i as u32, *xyz)?;
}
let mut body_tags = Vec::with_capacity(inputs.len());
for b in &inputs {
@@ -220,15 +235,15 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
}
for e in 0..m.element_count() {
let cell = cm.element_cell.get(e).map_or(0, |&c| c as usize);
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| i + 1).collect();
model.set_element(label(e)?, m.kind, nodes)?;
model.tag_element(label(e)?, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
let l = first_element + e as u32;
model.set_element(l, m.kind, nodes)?;
model.tag_element(l, body_tags.get(cell).copied().ok_or_else(|| EngineError::Params("element without a cell".into()))?)?;
}
tag_faces(&mut model, &inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, 1)?;
s.model = model;
tag_faces(model, &inputs, |e| cm.element_cell.get(e as usize).map_or(0, |&c| c as usize), &m.boundary, first_element)?;
let blocks: Vec<Value> =
inputs.iter().zip(&cm.blocks).map(|(b, d)| json!({"body": b.name, "divisions": d, "elements": d.iter().product::<usize>()})).collect();
Ok(json!({
let reply = json!({
"cells": inputs.len(),
"interfaces": cm.interfaces,
"description": m.report.description,
@@ -241,12 +256,8 @@ fn hex_blocks(s: &mut Session, p: &Value) -> Result<Value> {
"surface_volume": m.report.surface_volume,
"size": h,
"blocks": blocks,
}))
}
/// A 1-based model label for 0-based index `i`.
fn label(i: usize) -> Result<u32> {
u32::try_from(i).ok().and_then(|x| x.checked_add(1)).ok_or_else(|| EngineError::Params("too many nodes or elements".into()))
});
Ok(cleared.report(s, reply))
}
/// The `order` parameter: false for hex8, true for hex20.
@@ -256,7 +267,7 @@ fn order(p: &Value) -> Result<bool> {
Some(v) => match v.as_u64() {
Some(1) => Ok(false),
Some(2) => Ok(true),
_ => Err(EngineError::Params("`order` must be 1 (hex8) or 2 (hex20)".into())),
_ => Err(EngineError::invalid("order", "must be 1 (hex8) or 2 (hex20)")),
},
}
}
@@ -288,41 +299,16 @@ fn generate(s: &mut Session, p: &Value, default: HexMethod, allowed: &[HexMethod
let bodies = inputs(s, p)?;
let mut meshes: Vec<(Input, HexMesh)> = Vec::with_capacity(bodies.len());
for b in bodies {
if !(b.diagonal > 0.0 && b.diagonal.is_finite()) {
return Err(EngineError::Params(format!("body `{}` has no extent", b.name)));
}
let h = size.unwrap_or(DEFAULT_RELATIVE_SIZE * b.diagonal);
if h < MIN_RELATIVE_SIZE * b.diagonal {
return Err(EngineError::Params(format!("`size` must be at least {} mm for body `{}`", MIN_RELATIVE_SIZE * b.diagonal, b.name)));
}
let surface_options = super::mesh::surface_options(p, &b.mesh)?;
let surface = BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &surface_options)
.map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
let chord = if b.surfaces.is_empty() { 0.0 } else { number(p, "tolerance")?.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * b.diagonal) };
let options =
HexOptions { method, quadratic, chordal_tolerance: chord, max_elements: fieldcraft_model::MAX_ELEMENTS / 8, ..HexOptions::default() };
let mesh = hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
let mesh = hex_body(p, &b, method, quadratic, size)?;
meshes.push((b, mesh));
}
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
let mut model = s.model.without_mesh();
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
// A copy: the inputs borrow the session.
let mut model = s.model.clone();
let cleared = super::replace::clear(&mut model, meshes.iter().map(|(b, _)| b.name.as_str()));
let mut report = Vec::with_capacity(meshes.len());
let (mut node_label, mut element_label) = (1u32, 1u32);
for (b, m) in &meshes {
let first_node = node_label;
for xyz in &m.nodes {
model.set_node(node_label, *xyz)?;
node_label = node_label.checked_add(1).ok_or_else(|| EngineError::Params("too many nodes".into()))?;
}
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
let first_element = element_label;
for e in 0..m.element_count() {
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
model.set_element(element_label, m.kind, nodes)?;
model.tag_element(element_label, body_tag)?;
element_label = element_label.checked_add(1).ok_or_else(|| EngineError::Params("too many elements".into()))?;
}
tag_faces(&mut model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
add_hex(&mut model, b, m)?;
report.push(json!({
"body": b.name,
"method": m.report.method.name(),
@@ -336,8 +322,53 @@ fn generate(s: &mut Session, p: &Value, default: HexMethod, allowed: &[HexMethod
"surface_volume": m.report.surface_volume,
}));
}
let (nodes, elements) = (model.nodes().len(), model.elements().len());
s.model = model;
Ok(json!({"bodies": report, "nodes": node_label - 1, "elements": element_label - 1}))
Ok(cleared.report(s, json!({"bodies": report, "nodes": nodes, "elements": elements})))
}
/// Mesh one body with `method` (hex20 when `quadratic`) at `size` (default: from its extent);
/// the model is not touched. Errors name the body.
pub(super) fn hex_body(p: &Value, b: &Input, method: HexMethod, quadratic: bool, size: Option<f64>) -> Result<HexMesh> {
if !(b.diagonal > 0.0 && b.diagonal.is_finite()) {
return Err(EngineError::Params(format!("body `{}` has no extent", b.name)));
}
let h = size.unwrap_or(DEFAULT_RELATIVE_SIZE * b.diagonal);
if h < MIN_RELATIVE_SIZE * b.diagonal {
return Err(EngineError::Params(format!("`size` must be at least {} mm for body `{}`", MIN_RELATIVE_SIZE * b.diagonal, b.name)));
}
let surface_options = super::mesh::surface_options(p, &b.mesh)?;
let surface = BoundarySurface::new(&b.mesh.positions, &b.mesh.triangles, &b.mesh.tri_face, &surface_options)
.map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))?;
let chord = if b.surfaces.is_empty() { 0.0 } else { number(p, "tolerance")?.unwrap_or(DEFAULT_RELATIVE_TOLERANCE * b.diagonal) };
let options = HexOptions {
method,
quadratic,
chordal_tolerance: chord,
max_elements: fieldcraft_model::MAX_ELEMENTS / 8,
seeds: b.seeds.clone(),
..HexOptions::default()
};
hex_mesh(&surface, &b.surfaces, &UniformSize(h), &options).map_err(|e| EngineError::Params(format!("body `{}`: {e}", b.name)))
}
/// Add one body's hex mesh after the model's largest labels, tagging the elements with the body
/// and the boundary element faces with its B-rep faces; returns the first node and element
/// labels.
pub(super) fn add_hex(model: &mut Model, b: &Input, m: &HexMesh) -> Result<(u32, u32)> {
let (first_node, first_element) = super::fresh_labels(model, m.nodes.len(), m.element_count())?;
for (i, xyz) in m.nodes.iter().enumerate() {
model.set_node(first_node + i as u32, *xyz)?;
}
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
for e in 0..m.element_count() {
let nodes: Vec<u32> = m.element(e).unwrap_or(&[]).iter().map(|&i| first_node + i).collect();
let l = first_element + e as u32;
model.set_element(l, m.kind, nodes)?;
model.tag_element(l, body_tag)?;
}
tag_faces(model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
Ok((first_node, first_element))
}
/// Tag every boundary element face with the B-rep face it lies on, of the body
@@ -471,6 +502,22 @@ mod tests {
assert_eq!(two["cells"], 2);
}
/// The Partitioned Mesh form's "All hex" option is mesh.hex.blocks.
#[test]
fn mesh_cells_all_blocks_is_mesh_hex_blocks() {
let (_dir, mut s) = split_box(false);
let blocks = s.execute("mesh.hex.blocks", &json!({"size": 2.5})).unwrap();
let mut cells = s.execute("mesh.cells", &json!({"default": "blocks", "size": 2.5})).unwrap();
let mut blocks = blocks;
// The same mesh, in place of the first one.
let replaced = cells.as_object_mut().and_then(|o| o.remove("replaced")).unwrap();
assert_eq!(replaced.as_array().map(Vec::len), Some(4), "{replaced}");
blocks.as_object_mut().and_then(|o| o.remove("replaced"));
assert_eq!(cells, blocks);
let e = s.execute("mesh.cells", &json!({"default": "blocks", "methods": {"Box": "tet"}})).unwrap_err().to_string();
assert!(e.contains("methods"), "{e}");
}
#[test]
fn cells_that_do_not_conform_and_hostile_params_are_errors() {
let (_dir, mut s) = split_box(true);
+87 -48
View File
@@ -1,3 +1,4 @@
use crate::schema::ProblemKind;
use std::borrow::Cow;
use std::collections::BTreeMap;
@@ -13,6 +14,7 @@ use fieldcraft_model::{ElementKind, GeometryRef, MAX_ELEMENTS};
use serde_json::{Value, json};
use super::{label, labels, listed, optional_number, points, xyz};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const NODE_ADD: CommandSpec = CommandSpec {
@@ -21,6 +23,7 @@ pub const NODE_ADD: CommandSpec = CommandSpec {
params: r#"{"label": 1, "xyz": [x, y, z]} — adds the node, or moves it if the label exists"#,
form: Some(super::forms::NODE_ADD),
kind: CommandKind::Model,
requires: &[],
run: node_add,
};
@@ -30,6 +33,7 @@ pub const NODE_REMOVE: CommandSpec = CommandSpec {
params: r#"{"label": 1} — only a node no element uses"#,
form: Some(super::forms::LABEL),
kind: CommandKind::Model,
requires: &[Requirement::Nodes],
run: node_remove,
};
@@ -39,6 +43,7 @@ pub const ELEMENT_ADD: CommandSpec = CommandSpec {
params: r#"{"label": 1, "kind": "rod2|beam2|tri3|tri6|quad4|quad8|tet4|tet10|wedge6|hex8|hex20", "nodes": [labels]} — adds or replaces"#,
form: Some(super::forms::ELEMENT_ADD),
kind: CommandKind::Model,
requires: &[Requirement::Nodes],
run: element_add,
};
@@ -48,6 +53,7 @@ pub const ELEMENT_REMOVE: CommandSpec = CommandSpec {
params: r#"{"label": 1}"#,
form: Some(super::forms::LABEL),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: element_remove,
};
@@ -57,6 +63,7 @@ pub const QUALITY: CommandSpec = CommandSpec {
params: r#"{"elements": [labels] (optional, default all), "bins": 10 (1..=1000)} — certified validity (det J > 0 everywhere), volume, and min/max/mean/worst/histogram per metric (angles in degrees; histograms over each metric's fixed range, out-of-range values in the end bins)"#,
form: Some(super::forms::QUALITY),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: quality_report,
};
@@ -66,6 +73,7 @@ pub const DELAUNAY_POINTS: CommandSpec = CommandSpec {
params: r#"{"points": [[x, y, z], ...] (at most 20000)} — the exact Delaunay tetrahedralization (a debugging report; the model is not changed): {"dimension", "vertices", "duplicates": [[point, kept point], ...], "tets": [[i, j, k, l], ...]} with 0-based point indices in tet4 order; collinear or coplanar points give no tets"#,
form: Some(super::forms::DELAUNAY_POINTS),
kind: CommandKind::Model,
requires: &[],
run: delaunay_points,
};
@@ -92,15 +100,17 @@ pub const SURFACE_CHECK: CommandSpec = CommandSpec {
params: r#"{"body": "Body1", "tolerance": 0.05} or {"surface": 0}, optional "weld": 1e-9 (0 or 1e-15..=1e-3 of the bounding-box diagonal), "weld_distance": mm (default: the surface's own, twice SolidCraft's linear tolerance for a tessellated body, 0 for an imported mesh), "feature_angle": 45 (degrees, (0, 180]) — welds the tessellated body or imported surface and checks it can bound a volume mesh: closed, manifold, outward, no self-intersections; reports shells, genus, volume and feature edges, or the located defects"#,
form: Some(super::forms::SURFACE_CHECK),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: surface_check,
};
pub const TET_GENERATE: CommandSpec = CommandSpec {
id: "mesh.tet.generate",
label: "Generate Tet Mesh",
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the body's bounding-box diagonal), the boundary options of mesh.surface.check ("weld", "weld_distance", "feature_angle"), optional "size": mm (target edge length; default a twentieth of the bounding-box diagonal), "order": "linear" | "quadratic" (tet4 or tet10; quadratic mid-edge nodes lie on the B-rep faces), "quality": true (false: the raw constrained Delaunay tetrahedralization), "quality_target": 40 (degrees: tetrahedra whose smallest dihedral-angle sine is at least sin of this are left alone by improvement, 5..=60), "curvature_angle": 22.5 (degrees per element along curved boundary, 0 for none, at most 90), "grading": 0.3 (largest size change per unit length, 0.05..=2), "max_passes": 20 (improvement passes, 0..=200), "max_points": 1000000 (1..=20000000), "max_steiner": 50000 (0..=10000000), "max_tets": 5000000 (1..=50000000) — the constrained Delaunay tetrahedralization of the welded boundary (every boundary triangle a union of tet faces), refined to the size field with its boundary vertices on the B-rep faces, smoothed and improved (Delaunay refinement, ODT smoothing, Klingner–Shewchuk improvement), with a quality report. Adds the elements and their nodes (labels after the largest existing ones), tags the elements with the body and each boundary element face with its geometry face, and fails, changing nothing, if a surface is invalid or a mesh does not pass the validity gate. Reports the totals and, under `bodies`, each body's counts, size and quality report"#,
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the body's bounding-box diagonal), the boundary options of mesh.surface.check ("weld", "weld_distance", "feature_angle"), optional "size": mm (target edge length; default a twentieth of the bounding-box diagonal), "order": "linear" | "quadratic" (tet4 or tet10; quadratic mid-edge nodes lie on the B-rep faces), "quality": true (false: the raw constrained Delaunay tetrahedralization), "quality_target": 40 (degrees: tetrahedra whose smallest dihedral-angle sine is at least sin of this are left alone by improvement, 5..=60), "curvature_angle": 22.5 (degrees per element along curved boundary, 0 for none, at most 90), "grading": 0.3 (largest size change per unit length, 0.05..=2), "max_passes": 20 (improvement passes, 0..=200), "max_points": 1000000 (1..=20000000), "max_steiner": 50000 (0..=10000000), "max_tets": 5000000 (1..=50000000) — the constrained Delaunay tetrahedralization of the welded boundary (every boundary triangle a union of tet faces), refined to the size field with its boundary vertices on the B-rep faces, smoothed and improved (Delaunay refinement, ODT smoothing, Klingner–Shewchuk improvement), with a quality report. Replaces the mesh of each body it meshes (its elements and the nodes only they use; other bodies' meshes stay; the reply's `replaced`, `stale_sets` and `results_cleared` say what went), adds the elements and their nodes (labels after the largest existing ones), tags the elements with the body and each boundary element face with its geometry face, and fails, changing nothing, if a surface is invalid or a mesh does not pass the validity gate. Edge seeds (mesh.seed.edge) divide their edges at the seeded nodes, and the size field grades from them. Reports the totals and, under `bodies`, each body's counts, size, quality report and `seeds` (per seeded edge, the mesh edges along it)"#,
form: Some(super::forms::TET),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: tet_generate,
};
@@ -114,12 +124,15 @@ const TET_MAX_PASSES: u64 = 200;
pub(super) fn optional_count(p: &Value, key: &str, default: u64, range: std::ops::RangeInclusive<u64>) -> Result<usize> {
let v = match p.get(key) {
None => default,
Some(v) => v
.as_u64()
.filter(|n| range.contains(n))
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a whole number in {}..={}", range.start(), range.end())))?,
Some(v) => v.as_u64().filter(|n| range.contains(n)).ok_or_else(|| EngineError::param(key, whole_in(&range)))?,
};
usize::try_from(v).map_err(|_| EngineError::Params(format!("`{key}` is too large")))
usize::try_from(v).map_err(|_| EngineError::param(key, whole_in(&range)))
}
/// A whole number in `range`, as a problem's kind.
fn whole_in(range: &std::ops::RangeInclusive<u64>) -> ProblemKind {
let int = |n: u64| i64::try_from(n).unwrap_or(i64::MAX);
ProblemKind::NotAWholeNumber { min: int(*range.start()), max: int(*range.end()) }
}
/// The boundary options of `mesh.surface.check`, `mesh.tet.generate` and the hex meshers.
@@ -135,18 +148,18 @@ pub(super) fn surface_options(p: &Value, mesh: &SurfaceMesh) -> Result<SurfaceOp
/// An optional number in `range`.
fn number_in(p: &Value, key: &str, default: f64, range: std::ops::RangeInclusive<f64>) -> Result<f64> {
let v = optional_number(p, key, default)?;
if range.contains(&v) { Ok(v) } else { Err(EngineError::Params(format!("`{key}` must be a number in {}..={}", range.start(), range.end()))) }
if range.contains(&v) { Ok(v) } else { Err(EngineError::param(key, ProblemKind::NotInRange { min: *range.start(), max: *range.end() })) }
}
/// The quality options of `mesh.tet.generate`, and whether the quality stage runs at all.
fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
pub(super) fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
let d = QualityOptions::default();
let size = match p.get("size") {
None => None,
Some(v) => Some(
v.as_f64()
.filter(|h| *h > 0.0 && h.is_finite() && *h <= fieldcraft_model::MAX_COORD)
.ok_or_else(|| EngineError::Params("`size` must be a positive number (mm)".into()))?,
.ok_or_else(|| EngineError::param("size", ProblemKind::NotPositive))?,
),
};
let order = match p.get("order") {
@@ -154,7 +167,7 @@ fn quality_options(p: &Value, max_tets: u64) -> Result<(QualityOptions, bool)> {
Some(v) => match v.as_str() {
Some("linear") => Order::Linear,
Some("quadratic") => Order::Quadratic,
_ => return Err(EngineError::Params("`order` must be \"linear\" or \"quadratic\"".into())),
_ => return Err(EngineError::param("order", ProblemKind::NotAChoice)),
},
};
let target = number_in(p, "quality_target", 40.0, 5.0..=60.0)?;
@@ -200,7 +213,7 @@ pub fn analytic_surfaces(shape: &fieldcraft_geometry::Shape) -> Vec<Option<Analy
.collect()
}
fn quality_json(q: &TetQuality) -> Value {
pub(super) fn quality_json(q: &TetQuality) -> Value {
json!({
"tets": q.tets,
"min_dihedral": q.min_dihedral,
@@ -213,10 +226,10 @@ fn quality_json(q: &TetQuality) -> Value {
}
/// One body's tetrahedra, ready to add, with what its report needs of the surface and the CDT.
struct BodyTets {
name: String,
face_names: Vec<String>,
mesh: QualityMesh,
pub(super) struct BodyTets {
pub(super) name: String,
pub(super) face_names: Vec<String>,
pub(super) mesh: QualityMesh,
steiner: usize,
cavities: usize,
surface_volume: f64,
@@ -224,7 +237,7 @@ struct BodyTets {
/// Mesh one body or imported surface; the model is not touched. With `several` bodies an error
/// names the body.
fn mesh_body(
pub(super) fn mesh_body(
s: &Session,
p: &Value,
input: super::hex::Input,
@@ -241,7 +254,12 @@ fn mesh_body(
};
let surface = BoundarySurface::new(&input.mesh.positions, &input.mesh.triangles, &input.mesh.tri_face, &surface_options(p, &input.mesh)?)?;
let tets = tetrahedralize(&surface, cdt)?;
let mesh = if quality { quality_mesh(&surface, &tets, analytic, options)? } else { raw_mesh(&surface, &tets)? };
let mesh = if quality {
let options = QualityOptions { seeds: input.seeds.clone(), ..options.clone() };
quality_mesh(&surface, &tets, analytic, &options)?
} else {
raw_mesh(&surface, &tets)?
};
Ok(BodyTets {
name: input.name.clone(),
face_names: input.face_names.clone(),
@@ -266,9 +284,11 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
meshed.push(mesh_body(s, p, input, &cdt_options, &options, quality, several)?);
}
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
let cleared = super::replace::clear(&mut s.model, meshed.iter().map(|b| b.name.as_str()));
let mut bodies = Vec::with_capacity(meshed.len());
for b in &meshed {
let (first_node, first_element) = add_tets(s, &b.name, &b.face_names, &b.mesh)?;
let (first_node, first_element) = add_tets(&mut s.model, &b.name, &b.face_names, &b.mesh)?;
let r = &b.mesh.report;
bodies.push(json!({
"body": b.name,
@@ -292,12 +312,13 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
"straightened": r.straightened,
"stopped": r.stopped,
},
"seeds": r.seeds.iter().map(|(name, count, edges)| json!({"edge": name, "count": count, "mesh_edges": edges})).collect::<Vec<_>>(),
}));
}
let sum = |f: fn(&BodyTets) -> f64| meshed.iter().map(f).sum::<f64>();
let count = |f: fn(&BodyTets) -> usize| meshed.iter().map(f).sum::<usize>();
let first = bodies.first();
Ok(json!({
let reply = json!({
"kind": meshed.first().map(|b| b.mesh.kind.name()),
"nodes": count(|b| b.mesh.points.len()),
"elements": count(|b| b.mesh.elements.len()),
@@ -308,21 +329,22 @@ fn tet_generate(s: &mut Session, p: &Value) -> Result<Value> {
"boundary_volume": sum(|b| b.mesh.report.boundary_volume),
"surface_volume": sum(|b| b.surface_volume),
"bodies": bodies,
}))
});
Ok(cleared.report(s, reply))
}
/// Add one body's elements after the model's largest labels, tagging them with the body and each
/// boundary element face with its geometry face; returns the first node and element labels.
fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMesh) -> Result<(u32, u32)> {
let (first_node, first_element) = super::fresh_labels(&s.model, mesh.points.len(), mesh.elements.len())?;
pub(super) fn add_tets(model: &mut fieldcraft_model::Model, body: &str, face_names: &[String], mesh: &QualityMesh) -> Result<(u32, u32)> {
let (first_node, first_element) = super::fresh_labels(model, mesh.points.len(), mesh.elements.len())?;
for (i, xyz) in mesh.points.iter().enumerate() {
s.model.set_node(first_node + i as u32, *xyz)?;
model.set_node(first_node + i as u32, *xyz)?;
}
let body_tag = s.model.geometry_tag(&GeometryRef::body(body)?)?;
let body_tag = model.geometry_tag(&GeometryRef::body(body)?)?;
for (i, e) in mesh.elements.iter().enumerate() {
let label = first_element + i as u32;
s.model.set_element(label, mesh.kind, e.iter().map(|&v| first_node + v).collect())?;
s.model.tag_element(label, body_tag)?;
model.set_element(label, mesh.kind, e.iter().map(|&v| first_node + v).collect())?;
model.tag_element(label, body_tag)?;
}
let mut face_tags: Vec<Option<u32>> = vec![None; face_names.len()];
for b in &mesh.boundary {
@@ -331,7 +353,7 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
Some(t) => t,
None => {
let name = face_names.get(face).ok_or_else(|| EngineError::Params(format!("boundary face {} has no geometry face", b.face)))?;
let t = s.model.geometry_tag(&GeometryRef::face(body, name.clone())?)?;
let t = model.geometry_tag(&GeometryRef::face(body, name.clone())?)?;
if let Some(slot) = face_tags.get_mut(face) {
*slot = Some(t);
}
@@ -339,7 +361,7 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
}
};
let number = b.element_face().ok_or_else(|| EngineError::Params(format!("boundary face {} has no element face number", b.opposite)))?;
s.model.tag_element_face(first_element + b.tet, number, tag)?;
model.tag_element_face(first_element + b.tet, number, tag)?;
}
Ok((first_node, first_element))
}
@@ -347,9 +369,10 @@ fn add_tets(s: &mut Session, body: &str, face_names: &[String], mesh: &QualityMe
pub const PLANAR: CommandSpec = CommandSpec {
id: "mesh.planar",
label: "2D Mesh",
params: r#"{"size": 1.0, "kind": "quad4|quad8|tri3|tri6" (default quad4), and either "polygon": [[x, y], ...] with optional "holes": [[[x, y], ...], ...] and "name": "Plane" (the body name its tags use), or "body": "Body1", "face": "F2:top", "tolerance": 0.05 (a planar face of an open design, parallel to XY); optional "max_elements": 1000000 (1..=4000000)} — meshes the planar region with 2D elements in the XY plane (a face at z = c is meshed at z = 0) for plane stress, plane strain or axisymmetric sections (x the radius, Y the axis): free quadrilaterals (or constrained Delaunay triangles) of about `size`, mid-side nodes on the boundary for quadratic kinds. Adds nodes and elements after the largest existing labels and tags them: the elements with the face (polygon: face `area` of body `name`), the boundary element edges with edges named after the neighbouring face of the body (polygon: `e1`, `e2`, … side by side, the outer loop then each hole, and vertices `v1`, … at the corners), so sets on those edges carry loads and boundary conditions"#,
params: r#"{"size": 1.0, "kind": "quad4|quad8|tri3|tri6" (default quad4), and either "polygon": [[x, y], ...] with optional "holes": [[[x, y], ...], ...] and "name": "Plane" (the body name its tags use), or "body": "Body1", "face": "F2:top", "tolerance": 0.05 (a planar face of an open design, parallel to XY); optional "max_elements": 1000000 (1..=4000000)} — meshes the planar region with 2D elements in the XY plane (a face at z = c is meshed at z = 0) for plane stress, plane strain or axisymmetric sections (x the radius, Y the axis): free quadrilaterals (or constrained Delaunay triangles) of about `size`, mid-side nodes on the boundary for quadratic kinds. Replaces the body's mesh (as mesh.tet.generate), then adds nodes and elements after the largest existing labels and tags them: the elements with the face (polygon: face `area` of body `name`), the boundary element edges with edges named after the neighbouring face of the body (polygon: `e1`, `e2`, … side by side, the outer loop then each hole, and vertices `v1`, … at the corners), so sets on those edges carry loads and boundary conditions"#,
form: Some(super::forms::PLANAR),
kind: CommandKind::Model,
requires: &[],
run: planar,
};
@@ -379,14 +402,14 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
.get("size")
.and_then(Value::as_f64)
.filter(|v| *v > 0.0 && v.is_finite())
.ok_or_else(|| EngineError::Params("`size` must be a positive number (the element size)".into()))?;
.ok_or_else(|| super::wrong(p, "size", ProblemKind::NotPositive))?;
let kind = match p.get("kind") {
None => ElementKind::Quad4,
Some(k) => k
.as_str()
.and_then(ElementKind::from_name)
.filter(|k| k.dimension() == 2)
.ok_or_else(|| EngineError::Params("`kind` must be quad4, quad8, tri3 or tri6".into()))?,
.ok_or_else(|| EngineError::param("kind", ProblemKind::NotAChoice))?,
};
let opts = fieldcraft_mesh::quad::QuadOptions {
max_elements: optional_count(p, "max_elements", 1_000_000, 1..=PLANAR_MAX_ELEMENTS)?,
@@ -408,7 +431,7 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
}
let name = match p.get("name") {
None => "Plane".to_string(),
Some(n) => n.as_str().map(str::to_string).ok_or_else(|| EngineError::Params("`name` must be a body name".into()))?,
Some(n) => n.as_str().map(str::to_string).ok_or_else(|| EngineError::param("name", ProblemKind::NotAName))?,
};
GeometryRef::body(name.clone())?;
let mut id = 0u32;
@@ -428,7 +451,7 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
(loops, name, "area".to_string(), names)
}
(None, Some(_)) => {
let face_name = p.get("face").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`face` must be a face name".into()))?;
let face_name = p.get("face").and_then(Value::as_str).ok_or_else(|| EngineError::param("face", ProblemKind::NotAName))?;
let (shape, mesh) = super::geometry::body_mesh(s, p)?;
let face = shape.face_index(face_name).ok_or_else(|| EngineError::Params(format!("body `{}` has no face `{face_name}`", shape.name)))?;
let b = face_boundary(&mesh.positions, &mesh.triangles, &mesh.tri_face, face, mesh.weld_distance)?;
@@ -439,6 +462,8 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
};
let m = mesh_region(&loops, kind, size, &opts)?;
// Replace the body's mesh (replace.rs); other bodies and the definitions stay.
let cleared = super::replace::clear(&mut s.model, [body.as_str()]);
let (first_node, first_element) = super::fresh_labels(&s.model, m.nodes.len(), m.elements.len())?;
for (i, xy) in m.nodes.iter().enumerate() {
s.model.set_node(first_node + i as u32, [xy[0], xy[1], 0.0])?;
@@ -469,8 +494,8 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
s.model.tag_node(first_node + node, t)?;
}
}
let edges: Vec<&String> = tags.keys().filter_map(|id| names.get(id)).collect();
Ok(json!({
let edges: Vec<String> = tags.keys().filter_map(|id| names.get(id)).cloned().collect();
let reply = json!({
"body": body,
"face": face,
"kind": kind.name(),
@@ -479,7 +504,18 @@ fn planar(s: &mut Session, p: &Value) -> Result<Value> {
"first_node": first_node,
"first_element": first_element,
"edges": edges,
}))
});
Ok(cleared.report(s, reply))
}
/// The body `mesh.planar` fills: `body`, or the polygon's `name` (default `Plane`).
pub(super) fn planar_body(_: &Session, p: &Value) -> Result<Vec<String>> {
let name = match (p.get("polygon"), p.get("body")) {
(Some(_), None) => p.get("name").map_or(Some("Plane"), Value::as_str),
(None, Some(b)) => b.as_str(),
_ => None,
};
Ok(vec![name.ok_or_else(|| EngineError::Params("give either `polygon` or `body`".into()))?.to_string()])
}
fn node_add(s: &mut Session, p: &Value) -> Result<Value> {
@@ -518,7 +554,7 @@ fn number(v: f64) -> Value {
fn quality_report(s: &mut Session, p: &Value) -> Result<Value> {
let bins = match p.get("bins") {
None => 10,
Some(v) => v.as_u64().and_then(|b| usize::try_from(b).ok()).ok_or_else(|| EngineError::Params("`bins` must be a whole number".into()))?,
Some(v) => v.as_u64().and_then(|b| usize::try_from(b).ok()).ok_or_else(|| EngineError::invalid("bins", "must be a whole number"))?,
};
let selection = match p.get("elements") {
None => None,
@@ -745,8 +781,9 @@ mod tests {
// A tagged tetrahedron, and the same with a face missing.
let p = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
let t = vec![[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]];
let tet = SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0 };
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0 };
let tet =
SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
for mesh in [tet, open] {
s.surfaces.push(Arc::new(TaggedSurface { name: "Tet".into(), mesh, faces: 2 }));
}
@@ -776,7 +813,7 @@ mod tests {
}
#[test]
fn tet_generate_meshes_a_body_with_tags_and_appends() {
fn tet_generate_meshes_a_body_with_tags_and_replaces_its_mesh() {
use std::sync::Arc;
use fieldcraft_geometry::open_design;
@@ -802,11 +839,12 @@ mod tests {
let q = s.execute("mesh.quality", &json!({})).unwrap();
assert_eq!(q["valid"].as_u64().unwrap() as usize, elements);
assert!(q["summary"].as_str().unwrap().starts_with(&format!("{elements} elements, all valid; scaled Jacobian min ")), "{q}");
// A second run appends after the existing labels.
// A second run replaces the body's mesh (#267).
let again = s.execute("mesh.tet.generate", &json!({"body": "Body1", "tolerance": 0.5})).unwrap();
assert_eq!(again["first_element"].as_u64().unwrap() as usize, elements + 1);
assert_eq!(s.model.elements().len(), 2 * elements);
assert_eq!(s.journal.len(), 2);
assert_eq!(again["replaced"][0]["elements"].as_u64().unwrap() as usize, elements, "{again}");
assert_eq!(s.model.elements().len(), elements);
// The same mesh again, under the same labels: nothing changed, so no undo step.
assert_eq!(s.journal.len(), 1);
let journal = s.journal.len();
let model = s.model.clone();
@@ -837,7 +875,7 @@ mod tests {
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (_dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
assert!(s.execute("mesh.tet.generate", &json!({})).unwrap_err().to_string().contains("open a design first"));
assert!(s.execute("mesh.tet.generate", &json!({})).unwrap_err().to_string().contains("Needs geometry"));
s.execute("geometry.open", &json!({"path": path})).unwrap();
let r = s.execute("mesh.tet.generate", &json!({})).unwrap();
let bodies = r["bodies"].as_array().unwrap();
@@ -860,7 +898,7 @@ mod tests {
#[test]
fn quality_summary_counts_invalid_elements() {
let mut s = Session::default();
assert_eq!(s.execute("mesh.quality", &json!({})).unwrap()["summary"], "no elements to measure");
assert!(matches!(s.execute("mesh.quality", &json!({})), Err(crate::EngineError::Unavailable(_))), "no elements to measure");
for (label, xyz) in [(1, [0, 0, 0]), (2, [1, 0, 0]), (3, [0, 1, 0]), (4, [0, 0, 1])] {
s.execute("mesh.node.add", &json!({"label": label, "xyz": xyz})).unwrap();
}
@@ -946,8 +984,9 @@ mod tests {
let p = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
let t = vec![[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]];
let tet = SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0 };
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0 };
let tet =
SurfaceMesh { positions: p.clone(), triangles: t.clone(), tri_face: vec![0, 1, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
let open = SurfaceMesh { positions: p, triangles: t[..3].to_vec(), tri_face: vec![0, 1, 1], weld_distance: 0.0, ..SurfaceMesh::default() };
let mut s = Session::default();
for mesh in [tet, open] {
s.surfaces.push(Arc::new(TaggedSurface { name: "Tet".into(), mesh, faces: 2 }));
+408
View File
@@ -0,0 +1,408 @@
//! `mesh.mirror`: the mesh of some bodies reflected across a plane, joined to them on it.
//!
//! The geometry tags of the image name what it is the image of: the body of the open design that
//! occupies the reflected place (the other half of a part cut on its symmetry plane, found by its
//! volume and centroid, or named in `as`), and on it the face each reflected boundary face lies
//! on (found by position). Without such a body the image is `<body>/mirror` with the source's
//! face names.
use crate::schema::ProblemKind;
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_geometry::Shape;
use fieldcraft_mesh::mirror::{mirror, reflected_edges, reflected_faces};
use fieldcraft_model::geometry::Entity;
use fieldcraft_model::{ElementFace, GeometryRef, Model};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const MIRROR: CommandSpec = CommandSpec {
id: "mesh.mirror",
label: "Mirror Mesh",
params: r#"{"plane": "Sym" (a datum plane) or {"point": [x, y, z], "normal": [nx, ny, nz]}, "bodies": ["Part/a"] (default: every body the mesh is tagged with), "as": {"Part/a": "Part/b"} (optional: the body each image is; default the design's body at the reflected place, else "<body>/mirror")} — replaces each image body's mesh (as mesh.tet.generate) with the reflection of the bodies' elements (tet4, tet10, wedge6, hex8, hex20) across the plane: each copy right-handed (its nodes in reflected order), the copies of the nodes on the plane merged with them so the mesh is conforming there, geometry tags carried to the image (its body, and on it the faces the reflected faces lie on, so sets by face name select both halves). Reports the elements and nodes added, the nodes shared on the plane and each image's body"#,
form: Some(super::forms::MIRROR),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: mirror_mesh,
};
/// Relative difference of volume and centroid (to the body's size) under which a body is the
/// image of another.
const SAME_PLACE: f64 = 1e-4;
/// Distance (relative to the mesh's bounding-box diagonal) within which nodes are on the plane.
const ON_PLANE: f64 = 1e-7;
fn not_a_plane() -> EngineError {
EngineError::invalid("plane", r#"must be a datum plane's name or {"point": [x, y, z], "normal": [x, y, z]}"#)
}
/// The plane: a datum plane by name, or a point and a normal.
fn plane(s: &Session, p: &Value) -> Result<([f64; 3], [f64; 3])> {
match p.get("plane") {
Some(Value::String(name)) => s
.model
.datum(name)
.and_then(|d| d.plane())
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", name.chars().take(64).collect::<String>()))),
Some(v @ Value::Object(_)) => match (super::xyz(v, "point"), super::xyz(v, "normal")) {
(Ok(point), Ok(normal)) => Ok((point, normal)),
_ => Err(not_a_plane()),
},
None | Some(Value::Null) => Err(EngineError::param("plane", ProblemKind::Required)),
_ => Err(not_a_plane()),
}
}
fn reflect(x: [f64; 3], point: [f64; 3], n: [f64; 3]) -> [f64; 3] {
let d: f64 = (0..3).map(|i| (x[i] - point[i]) * n[i]).sum();
[x[0] - 2.0 * d * n[0], x[1] - 2.0 * d * n[1], x[2] - 2.0 * d * n[2]]
}
/// The design body at the reflected place of `source`: the same volume and the reflected
/// centroid, within [`SAME_PLACE`] (the kernel measures curved bodies on a tessellation, so the
/// two halves of a symmetric part measure alike only to its accuracy).
fn image_body<'a>(bodies: &'a [Shape], source: &Shape, point: [f64; 3], n: [f64; 3]) -> Result<Option<&'a Shape>> {
let m = source.measure()?;
let size = source.size()?.max(1e-9);
let want = reflect(m.centroid, point, n);
for b in bodies.iter().filter(|b| b.name != source.name) {
let o = b.measure()?;
let d = (0..3).map(|k| (o.centroid[k] - want[k]).powi(2)).sum::<f64>().sqrt();
if (o.volume - m.volume).abs() <= SAME_PLACE * m.volume.abs().max(1e-12) && d <= SAME_PLACE * size {
return Ok(Some(b));
}
}
Ok(None)
}
/// What `mesh.mirror` reflects, across which plane, into which bodies.
struct Plan<'d> {
point: [f64; 3],
/// The plane's unit normal.
n: [f64; 3],
/// The elements reflected.
region: BTreeSet<u32>,
/// Each mirrored body's image: its name and, when the design has it, its shape.
image: BTreeMap<String, (String, Option<&'d Shape>)>,
}
fn plan<'d>(s: &Session, design: Option<&'d fieldcraft_geometry::Design>, p: &Value) -> Result<Plan<'d>> {
let (point, normal) = plane(s, p)?;
let len = normal.iter().map(|x| x * x).sum::<f64>().sqrt();
if !(len > 1e-12 && len.is_finite() && point.iter().all(|x| x.is_finite())) {
return Err(EngineError::Params("the plane needs a finite point and a non-zero normal".into()));
}
let n = normal.map(|x| x / len);
let c = s.model.classification();
// The bodies the mesh is tagged with, by tag.
let tagged: BTreeMap<u32, String> = c
.entities()
.iter()
.enumerate()
.filter(|(_, r)| r.entity == Entity::Body)
.filter_map(|(t, r)| Some((u32::try_from(t).ok()?, r.body.clone())))
.collect();
let bodies: Vec<String> = match p.get("bodies") {
None => {
let mut v: Vec<String> = tagged.values().cloned().collect();
v.dedup();
v
}
Some(_) => super::req(p, "bodies")?,
};
if bodies.is_empty() {
return Err(EngineError::Params("no body to mirror: the mesh is not tagged with a body".into()));
}
for b in &bodies {
if !tagged.values().any(|t| t == b) {
return Err(EngineError::Params(format!("the mesh has no elements of body `{}`", b.chars().take(64).collect::<String>())));
}
}
let named: BTreeMap<String, String> = super::opt(p, "as")?.unwrap_or_default();
let region: BTreeSet<u32> =
c.elements().iter().filter(|(_, t)| t.region.and_then(|r| tagged.get(&r)).is_some_and(|b| bodies.contains(b))).map(|(e, _)| *e).collect();
// The image of each body: named, found in the design, or its own `/mirror`.
let mut image: BTreeMap<String, (String, Option<&Shape>)> = BTreeMap::new();
for b in &bodies {
let source = design.and_then(|d| d.body(b));
let target = match named.get(b) {
Some(t) => (t.clone(), design.and_then(|d| d.body(t))),
None => match (design, source) {
(Some(d), Some(src)) => match image_body(&d.bodies, src, point, n)? {
Some(t) => (t.name.clone(), Some(t)),
None => (format!("{b}/mirror"), None),
},
_ => (format!("{b}/mirror"), None),
},
};
if bodies.contains(&target.0) {
return Err(EngineError::Params(format!("the image of `{b}` would be `{}`, which is mirrored too", target.0)));
}
image.insert(b.clone(), target);
}
Ok(Plan { point, n, region, image })
}
/// The bodies `mesh.mirror` fills: the images.
pub(super) fn image_names(s: &Session, p: &Value) -> Result<Vec<String>> {
Ok(plan(s, s.design.as_deref(), p)?.image.into_values().map(|(name, _)| name).collect())
}
fn mirror_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let design = s.design.clone();
let Plan { point, n, region, image } = plan(s, design.as_deref(), p)?;
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
for node in s.model.nodes().values() {
for k in 0..3 {
lo[k] = lo[k].min(node.xyz[k]);
hi[k] = hi[k].max(node.xyz[k]);
}
}
let diagonal = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::<f64>().sqrt().max(1e-9);
// An image body's earlier mesh is replaced (replace.rs).
let model = &mut s.model;
let cleared = super::replace::clear(model, image.values().map(|(name, _)| name.as_str()));
let before = model.clone();
let r = mirror(model, &region, point, n, ON_PLANE * diagonal).map_err(|e| EngineError::Params(e.to_string()))?;
tag_image(model, &before, &r, &image, point, n, diagonal)?;
let added_nodes = model.nodes().len() - before.nodes().len();
let images: Vec<Value> = image.iter().map(|(b, (t, shape))| json!({"body": b, "image": t, "in_design": shape.is_some()})).collect();
let reply = json!({
"elements": r.elements.len(),
"nodes": added_nodes,
"on_plane": r.on_plane,
"images": images,
"total": {"nodes": s.model.nodes().len(), "elements": s.model.elements().len()},
});
Ok(cleared.report(s, reply))
}
/// Tag the image: each copy with its image body, its faces with the faces of that body they lie
/// on (or the source's names), its edges and the images of tagged nodes with the source's names.
fn tag_image(
model: &mut Model,
before: &Model,
r: &fieldcraft_mesh::mirror::Mirrored,
image: &BTreeMap<String, (String, Option<&Shape>)>,
point: [f64; 3],
n: [f64; 3],
diagonal: f64,
) -> Result<()> {
let c = before.classification();
let entity = |t: u32| c.entity(t).cloned();
// A source face's image: by the image body's face under its reflected centroid, one lookup per
// face name (the first element face of it stands for all).
let mut face_points: BTreeMap<(String, String), [f64; 3]> = BTreeMap::new();
for (&e, tags) in c.elements() {
if !r.elements.contains_key(&e) {
continue;
}
for (&f, &t) in &tags.faces {
let Some(GeometryRef { body, entity: Entity::Face(name) }) = entity(t) else { continue };
if face_points.contains_key(&(body.clone(), name.clone())) {
continue;
}
let Some(nodes) = before.face_nodes(ElementFace { element: e, face: f }) else { continue };
let pts: Vec<[f64; 3]> = nodes.iter().filter_map(|n| before.node(*n).map(|x| x.xyz)).collect();
let k = pts.len().max(1) as f64;
let centre = [0, 1, 2].map(|i| pts.iter().map(|p| p[i]).sum::<f64>() / k);
face_points.insert((body, name), reflect(centre, point, n));
}
}
let mut face_names: BTreeMap<(String, String), (String, String)> = BTreeMap::new();
let mut by_body: BTreeMap<String, Vec<(String, [f64; 3])>> = BTreeMap::new();
for ((body, name), p) in &face_points {
by_body.entry(body.clone()).or_default().push((name.clone(), *p));
}
for (body, faces) in by_body {
let Some((target, shape)) = image.get(&body) else { continue };
let found = match shape {
Some(shape) => {
let pts: Vec<[f64; 3]> = faces.iter().map(|(_, p)| *p).collect();
shape.nearest_faces(&pts, (1e-3 * diagonal).max(1e-4))?
}
None => vec![None; faces.len()],
};
for ((name, _), f) in faces.iter().zip(found) {
let mapped = f.and_then(|f| shape.and_then(|s| s.faces().get(f as usize))).map_or_else(|| name.clone(), |x| x.name.clone());
face_names.insert((body.clone(), name.clone()), (target.clone(), mapped));
}
}
let mut tags: BTreeMap<GeometryRef, u32> = BTreeMap::new();
let mut tag = |model: &mut Model, r: GeometryRef| -> Result<u32> {
if let Some(&t) = tags.get(&r) {
return Ok(t);
}
let t = model.geometry_tag(&r)?;
tags.insert(r, t);
Ok(t)
};
for (&e, &copy) in &r.elements {
let Some(el) = before.element(e) else { continue };
let Some(t) = c.elements().get(&e) else { continue };
let faces = reflected_faces(el.kind).unwrap_or_default();
let edges = reflected_edges(el.kind).unwrap_or_default();
if let Some(GeometryRef { body, .. }) = t.region.and_then(entity)
&& let Some((target, _)) = image.get(&body)
{
let tg = tag(model, GeometryRef::body(target.as_str())?)?;
model.tag_element(copy, tg)?;
}
for (&f, &ft) in &t.faces {
let Some(GeometryRef { body, entity: Entity::Face(name) }) = entity(ft) else { continue };
let Some((tb, tn)) = face_names.get(&(body, name)) else { continue };
let g = faces.get(usize::from(f).saturating_sub(1)).copied().unwrap_or(f);
let tg = tag(model, GeometryRef::face(tb.as_str(), tn.as_str())?)?;
model.tag_element_face(copy, g, tg)?;
}
for (&k, &et) in &t.edges {
let Some(GeometryRef { body, entity: ent }) = entity(et) else { continue };
let Some((target, _)) = image.get(&body) else { continue };
let g = edges.get(usize::from(k).saturating_sub(1)).copied().unwrap_or(k);
let tg = tag(model, GeometryRef::new(target.as_str(), ent)?)?;
model.tag_element_edge(copy, g, tg)?;
}
}
for (&node, &copy) in &r.nodes {
if copy == node {
continue;
}
let Some(GeometryRef { body, entity: ent }) = c.nodes().get(&node).and_then(|&t| entity(t)) else { continue };
let Some((target, _)) = image.get(&body) else { continue };
let tg = tag(model, GeometryRef::new(target.as_str(), ent)?)?;
model.tag_node(copy, tg)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A session with a 40 × 10 × 10 bar (along x from the origin) open, partitioned at
/// x = 20 when `half`.
fn bar(half: bool) -> (crate::tests::TempDir, Session) {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
]});
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
let b = s.execute("geometry.bodies", &json!({})).unwrap()[0]["bbox"].clone();
let lo: Vec<f64> = b[0].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let hi: Vec<f64> = b[1].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert_eq!(lo, [0.0; 3]);
assert_eq!(hi, [40.0, 10.0, 10.0]);
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "yz", "offset": 20}})).unwrap();
if half {
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
}
(dir, s)
}
/// The face of `body` nearest to `point`.
fn face(s: &Session, body: &str, point: [f64; 3]) -> String {
let shape = s.design.as_ref().unwrap().body(body).unwrap();
let f = shape.nearest_faces(&[point], 0.01).unwrap()[0].unwrap();
shape.faces()[f as usize].name.clone()
}
/// Clamped at x = 0, 1 kN down on the end at x = 40 (sets by face name on the bodies given),
/// solved; the largest downward deflection and the mesh's volume and counts.
fn bend(s: &mut Session, root: (&str, String), tip: (&str, String)) -> (f64, f64, usize, usize) {
let all: Vec<Value> = s.design.as_ref().unwrap().bodies.iter().map(|b| json!({"body": b.name})).collect();
let script = json!([
{"command": "model.set.create", "params": {"name": "all", "geometry": all}},
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": root.0, "face": root.1}]}},
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": tip.0, "face": tip.1}]}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Steel", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"set": "tip"}, "vector": [0, 0, -1000]}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Push"]}},
]);
s.run_script(&script).unwrap();
s.execute("solve.static", &json!({})).unwrap();
let tip_nodes = s.model.resolve_set("tip").unwrap().nodes;
assert!(!tip_nodes.is_empty());
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip_nodes})).unwrap();
let w = probe["nodes"].as_array().unwrap().iter().map(|n| -n["displacement"][2].as_f64().unwrap()).fold(f64::MIN, f64::max);
let q = s.execute("mesh.quality", &json!({})).unwrap();
assert_eq!(q["valid"].as_u64().unwrap() as usize, s.model.elements().len(), "{q}");
(w, q["volume"].as_f64().unwrap(), s.model.nodes().len(), s.model.elements().len())
}
/// Half the bar meshed and mirrored is the whole bar meshed: the same counts and volume, and
/// the same bending deflection to round-off, hex8 and hex20; the image's faces carry the
/// whole bar's face names, so the load on the far end (a face of the image only) is found.
#[test]
fn a_mirrored_half_is_the_whole_mesh() {
for order in [1, 2] {
let (_d1, mut whole) = bar(false);
whole.execute("mesh.hex.mapped", &json!({"body": "Bar", "size": 2.5, "order": order})).unwrap();
let (root, tip) = (face(&whole, "Bar", [0.0, 5.0, 5.0]), face(&whole, "Bar", [40.0, 5.0, 5.0]));
let full = bend(&mut whole, ("Bar", root), ("Bar", tip));
let (_d2, mut half) = bar(true);
half.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 2.5, "order": order})).unwrap();
let r = half.execute("mesh.mirror", &json!({"plane": "Mid"})).unwrap();
assert_eq!(r["images"][0], json!({"body": "Bar/a", "image": "Bar/b", "in_design": true}), "{r}");
// 5 × 5 corner nodes on the plane (and 40 mid-edge nodes on it for hex20).
assert_eq!(r["on_plane"], json!(if order == 1 { 25 } else { 65 }), "{r}");
let (root, tip) = (face(&half, "Bar/a", [0.0, 5.0, 5.0]), face(&half, "Bar/b", [40.0, 5.0, 5.0]));
let mirrored = bend(&mut half, ("Bar/a", root), ("Bar/b", tip));
assert_eq!((mirrored.2, mirrored.3), (full.2, full.3), "order {order}: node and element counts");
assert!((mirrored.1 - full.1).abs() < 1e-9 * full.1, "order {order}: volume {} vs {}", mirrored.1, full.1);
assert!((mirrored.0 - full.0).abs() < 1e-9 * full.0, "order {order}: deflection {} vs {}", mirrored.0, full.0);
}
}
/// Tets of either order mirror into valid elements sharing the plane's nodes; the volume
/// doubles.
#[test]
fn mirrored_tets_are_valid_and_conforming() {
for order in ["linear", "quadratic"] {
let (_d, mut s) = bar(true);
s.execute("mesh.tet.generate", &json!({"body": "Bar/a", "size": 4, "order": order})).unwrap();
let v = s.execute("mesh.quality", &json!({})).unwrap()["volume"].as_f64().unwrap();
let r = s.execute("mesh.mirror", &json!({"plane": {"point": [20, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Bar/a"]})).unwrap();
assert!(r["on_plane"].as_u64().unwrap() > 0, "{r}");
let q = s.execute("mesh.quality", &json!({})).unwrap();
assert_eq!(q["valid"].as_u64().unwrap() as usize, s.model.elements().len(), "{q}");
assert!((q["volume"].as_f64().unwrap() - 2.0 * v).abs() < 1e-9 * v, "{q}");
// The plane's faces are interior now: the skin of both bodies is the bar's.
s.execute("model.set.create", &json!({"name": "a", "geometry": [{"body": "Bar/a"}]})).unwrap();
s.execute("model.set.create", &json!({"name": "b", "geometry": [{"body": "Bar/b"}]})).unwrap();
let (a, b) = (s.model.resolve_set("a").unwrap(), s.model.resolve_set("b").unwrap());
assert_eq!(a.elements.len(), b.elements.len());
assert_eq!(a.faces.len(), b.faces.len());
}
}
#[test]
fn hostile_params_change_nothing() {
let (_d, mut s) = bar(true);
s.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 5})).unwrap();
let model = s.model.clone();
for p in [
json!({}),
json!({"plane": "Nope"}),
json!({"plane": {"point": [0, 0, 0], "normal": [0, 0, 0]}}),
json!({"plane": {"point": [f64::MAX, 0, 0], "normal": [1, 0, 0]}}),
json!({"plane": {"point": [0, 0], "normal": [1, 0, 0]}}),
json!({"plane": "Mid", "bodies": ["Nope"]}),
json!({"plane": "Mid", "bodies": []}),
json!({"plane": "Mid", "as": {"Bar/a": "Bar/a"}}),
json!({"plane": "Mid", "as": "x"}),
] {
assert!(s.execute("mesh.mirror", &p).is_err(), "{p}");
}
assert_eq!(s.model, model);
}
}
+59 -12
View File
@@ -1,9 +1,12 @@
//! The command registry. Each area has its own module; [`ALL`] lists every command.
mod block;
mod cells;
mod contact;
pub(crate) mod datum;
pub(crate) mod deck;
pub(crate) mod define;
pub mod diagnostics;
mod edit;
pub(crate) mod file;
pub(crate) mod forms;
@@ -11,13 +14,21 @@ mod geometry;
mod hex;
pub(crate) mod mesh;
pub use datum::edit_params as datum_edit_params;
pub use mesh::analytic_surfaces;
mod mirror;
mod model;
pub(crate) mod octree;
pub mod replace;
mod results;
pub(crate) mod seeds;
pub(crate) mod solve;
mod symmetry;
mod tags;
pub mod update;
pub(crate) mod view;
use crate::schema::ProblemKind;
use fieldcraft_model::MAX_LABEL;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -32,6 +43,19 @@ pub static ALL: &[CommandSpec] = &[
geometry::BODIES,
geometry::TESSELLATE,
geometry::IMPORT_MESH,
datum::DATUM_PLANE,
datum::DATUM_AXIS,
datum::DATUM_POINT,
datum::DATUM_EDIT,
datum::DATUM_AXIS_EDIT,
datum::DATUM_POINT_EDIT,
datum::DATUM_DELETE,
view::HIDE,
view::SHOW,
view::ISOLATE,
view::SHOW_ALL,
datum::PARTITION,
datum::PARTITION_DELETE,
mesh::NODE_ADD,
mesh::NODE_REMOVE,
mesh::ELEMENT_ADD,
@@ -47,6 +71,11 @@ pub static ALL: &[CommandSpec] = &[
hex::HEX_SWEEP,
hex::HEX_MAPPED,
hex::HEX_BLOCKS,
cells::CELLS,
seeds::SEED_EDGE,
seeds::SEED_CLEAR,
seeds::SEED_LIST,
mirror::MIRROR,
tags::TAG,
tags::TAG_CLEAR,
model::UNITS,
@@ -74,6 +103,9 @@ pub static ALL: &[CommandSpec] = &[
contact::EDIT,
contact::DELETE,
contact::FIND,
contact::TIE,
contact::TIE_EDIT,
contact::TIE_DELETE,
define::MASS_CREATE,
define::MASS_EDIT,
define::MASS_DELETE,
@@ -83,6 +115,7 @@ pub static ALL: &[CommandSpec] = &[
define::BOUNDARY_CONDITION_CREATE,
define::BOUNDARY_CONDITION_EDIT,
define::BOUNDARY_CONDITION_DELETE,
symmetry::SYMMETRY,
define::LOAD_CREATE,
define::LOAD_EDIT,
define::LOAD_DELETE,
@@ -122,14 +155,25 @@ pub static ALL: &[CommandSpec] = &[
results::FRAME,
results::REACTIONS,
results::CLEAR,
diagnostics::CRASH_REPORTS,
diagnostics::CRASH_REPORT,
diagnostics::BUG_REPORT,
diagnostics::CRASH_TEST,
update::CHECK,
];
/// The problem with required parameter `key`: [`ProblemKind::Required`] when it is left out,
/// else `kind`.
pub(crate) fn wrong(p: &Value, key: &str, kind: ProblemKind) -> EngineError {
EngineError::param(key, if p.get(key).is_none_or(Value::is_null) { ProblemKind::Required } else { kind })
}
/// A required label parameter (1..=u32::MAX; the model checks its own range).
pub(crate) fn label(p: &Value, key: &str) -> Result<u32> {
p.get(key)
.and_then(Value::as_u64)
.and_then(|v| u32::try_from(v).ok())
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a positive whole number")))
.ok_or_else(|| wrong(p, key, ProblemKind::NotAWholeNumber { min: 1, max: i64::from(u32::MAX) }))
}
/// The first node and element labels after the model's largest, for `nodes` new nodes and
@@ -147,7 +191,7 @@ pub(crate) fn fresh_labels(model: &fieldcraft_model::Model, nodes: usize, elemen
/// A required `[x, y, z]` parameter.
pub(crate) fn xyz(p: &Value, key: &str) -> Result<[f64; 3]> {
p.get(key).and_then(xyz_value).ok_or_else(|| EngineError::Params(format!("`{key}` must be [x, y, z]")))
p.get(key).and_then(xyz_value).ok_or_else(|| wrong(p, key, ProblemKind::NotAVector { len: 3 }))
}
/// A JSON `[x, y, z]`.
@@ -160,9 +204,12 @@ fn xyz_value(v: &Value) -> Option<[f64; 3]> {
/// A required list of `[x, y, z]` points, at most `max_len` long.
pub(crate) fn points(p: &Value, key: &str, max_len: usize) -> Result<Vec<[f64; 3]>> {
let bad = |what: String| EngineError::Params(format!("`{key}` must be a list of at most {max_len} [x, y, z]{what}"));
let raw = p.get(key).and_then(Value::as_array).filter(|a| a.len() <= max_len).ok_or_else(|| bad(String::new()))?;
raw.iter().enumerate().map(|(i, v)| xyz_value(v).ok_or_else(|| bad(format!(" (entry {i} is not)")))).collect()
let raw = p.get(key).and_then(Value::as_array).filter(|a| a.len() <= max_len);
let raw = raw.ok_or_else(|| wrong(p, key, ProblemKind::NotAList { max: max_len, what: "[x, y, z]" }))?;
raw.iter()
.enumerate()
.map(|(i, v)| xyz_value(v).ok_or_else(|| EngineError::invalid(key, format!("must be a list of [x, y, z] (entry {i} is not)"))))
.collect()
}
/// A required list of labels (each in 1..=MAX_LABEL), at most `max_len` long.
@@ -171,11 +218,11 @@ pub(crate) fn labels(p: &Value, key: &str, max_len: usize) -> Result<Vec<u32>> {
.get(key)
.and_then(Value::as_array)
.filter(|a| a.len() <= max_len)
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a list of at most {max_len} labels")))?;
.ok_or_else(|| wrong(p, key, ProblemKind::NotAList { max: max_len, what: "labels" }))?;
raw.iter()
.map(|v| v.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| (1..=MAX_LABEL).contains(n)))
.collect::<Option<Vec<u32>>>()
.ok_or_else(|| EngineError::Params(format!("`{key}` must be labels in 1..={MAX_LABEL}")))
.ok_or_else(|| EngineError::invalid(key, format!("must be labels in 1..={MAX_LABEL}")))
}
/// A required path parameter, as given.
@@ -183,7 +230,7 @@ fn path_param<'a>(p: &'a Value, key: &str) -> Result<&'a str> {
p.get(key)
.and_then(Value::as_str)
.filter(|s| !s.trim().is_empty() && s.len() <= fieldcraft_io::MAX_PATH_LEN && !s.contains('\0'))
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a file path")))
.ok_or_else(|| wrong(p, key, ProblemKind::NotAPath))
}
/// A required path parameter naming a file (or folder) the command reads or writes: the path
@@ -198,23 +245,23 @@ pub(crate) fn file_param(s: &Session, p: &Value, key: &str, access: Access) -> R
pub(crate) fn optional_number(p: &Value, key: &str, default: f64) -> Result<f64> {
match p.get(key) {
None => Ok(default),
Some(v) => v.as_f64().ok_or_else(|| EngineError::Params(format!("`{key}` must be a number"))),
Some(v) => v.as_f64().ok_or_else(|| EngineError::param(key, ProblemKind::NotANumber)),
}
}
/// The `name` parameter.
pub(crate) fn name(p: &Value) -> Result<&str> {
p.get("name").and_then(Value::as_str).ok_or_else(|| EngineError::Params("`name` must be a name".into()))
p.get("name").and_then(Value::as_str).ok_or_else(|| wrong(p, "name", ProblemKind::NotAName))
}
/// An optional parameter read as `T`'s JSON form; `None` when it is absent.
pub(crate) fn opt<'a, T: Deserialize<'a>>(p: &'a Value, key: &str) -> Result<Option<T>> {
p.get(key).map(|v| T::deserialize(v).map_err(|e| EngineError::Params(format!("`{key}`: {e}")))).transpose()
p.get(key).map(|v| T::deserialize(v).map_err(|e| EngineError::invalid(key, format!("is not valid: {e}")))).transpose()
}
/// A required parameter read as `T`'s JSON form.
pub(crate) fn req<'a, T: Deserialize<'a>>(p: &'a Value, key: &str) -> Result<T> {
opt(p, key)?.ok_or_else(|| EngineError::Params(format!("`{key}` is required")))
opt(p, key)?.ok_or_else(|| EngineError::param(key, ProblemKind::Required))
}
/// Entries listed in a report: the first ones, and how many there are.
+8 -2
View File
@@ -2,10 +2,11 @@ use fieldcraft_model::{Severity, UnitSystem};
use serde_json::{Value, json};
use super::{listed, name};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const INFO: CommandSpec =
CommandSpec { id: "model.info", label: "Model Info", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: info };
CommandSpec { id: "model.info", label: "Model Info", params: "{}", form: Some(&[]), kind: CommandKind::Model, requires: &[], run: info };
pub const UNITS: CommandSpec = CommandSpec {
id: "model.units",
@@ -13,11 +14,12 @@ pub const UNITS: CommandSpec = CommandSpec {
params: r#"{"system": "m-kg-s-N-Pa|mm-t-s-N-MPa|mm-kg-ms-kN-GPa|mm-g-ms-N-MPa|in-lbf-s-psi|unspecified"} — labels the system the model's numbers are in; nothing is converted"#,
form: Some(super::forms::UNITS),
kind: CommandKind::Model,
requires: &[],
run: units,
};
pub const CHECK: CommandSpec =
CommandSpec { id: "model.check", label: "Check Model", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: check };
CommandSpec { id: "model.check", label: "Check Model", params: "{}", form: Some(&[]), kind: CommandKind::Model, requires: &[], run: check };
pub const SET_RESOLVE: CommandSpec = CommandSpec {
id: "model.set.resolve",
@@ -25,6 +27,7 @@ pub const SET_RESOLVE: CommandSpec = CommandSpec {
params: r#"{"name": "root"} — the set's nodes, elements and element faces on the current mesh (the first 100 of each); fails naming every member that is not on the mesh"#,
form: Some(super::forms::SET_RESOLVE),
kind: CommandKind::Model,
requires: &[Requirement::Set],
run: set_resolve,
};
@@ -54,11 +57,14 @@ fn units(s: &mut Session, p: &Value) -> Result<Value> {
fn check(s: &mut Session, _: &Value) -> Result<Value> {
let diagnostics = s.model.check();
let errors = diagnostics.iter().filter(|d| d.severity == Severity::Error).count();
let first_error = diagnostics.iter().find(|d| d.severity == Severity::Error).map(ToString::to_string);
let progress = crate::progress::to_json(&s.progress_given(first_error));
Ok(json!({
"ready": errors == 0,
"errors": errors,
"warnings": diagnostics.len() - errors,
"diagnostics": diagnostics,
"progress": progress,
}))
}
+15 -14
View File
@@ -9,14 +9,16 @@ use serde_json::{Value, json};
use super::hex::{Input, inputs, number, tag_faces};
use super::mesh::optional_count;
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const HEX_OCTREE: CommandSpec = CommandSpec {
id: "mesh.hex.octree",
label: "Octree Hex Mesh",
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size in the interior, mm; default 1/25 of the bounding-box diagonal), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal), "max_depth": 3 (refinement levels below the size, each a third, 0..=5), "max_elements": 2000000 (1..=10000000; default the session limit), "attempts": 4 (builds, refining where one failed, 1..=8), "max_sweeps": 300 (optimiser sweeps, 0..=10000), and the boundary options of mesh.tet.generate ("weld", "weld_distance", "feature_angle")} — replaces the mesh with an unstructured all-hex8 mesh of any part: an adaptive 3-refinement grid with conforming transition templates, a core inside the part, two boundary layers that capture every B-rep face boundary and sharp edge, and untangling. Every element is proven valid; boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name), so sets by geometry resolve. Reports per body the elements, quality, volume and grid statistics"#,
params: r#"{"body": "Body1" (default: every body of the open design) or "surface": 0 (an imported surface), "size": 2.0 (element size in the interior, mm; default 1/25 of the bounding-box diagonal), "tolerance": 0.05 (chordal tolerance of the tessellation, mm; default 1e-3 of the diagonal), "max_depth": 3 (refinement levels below the size, each a third, 0..=5), "max_elements": 2000000 (1..=10000000; default the session limit), "attempts": 4 (builds, refining where one failed, 1..=8), "max_sweeps": 300 (optimiser sweeps, 0..=10000), and the boundary options of mesh.tet.generate ("weld", "weld_distance", "feature_angle")} — replaces the meshes of the bodies it meshes (as mesh.tet.generate; other bodies keep theirs) with an unstructured all-hex8 mesh of any part: an adaptive 3-refinement grid with conforming transition templates, a core inside the part, two boundary layers that capture every B-rep face boundary and sharp edge, and untangling. Every element is proven valid; boundary element faces are tagged with their B-rep faces (named as in geometry.bodies; by index when a face has no name), so sets by geometry resolve. Reports per body the elements, quality, volume and grid statistics"#,
form: Some(super::forms::HEX_OCTREE),
kind: CommandKind::Model,
requires: &[Requirement::Geometry],
run: hex_octree,
};
@@ -62,22 +64,20 @@ fn hex_octree(s: &mut Session, p: &Value) -> Result<Value> {
total += mesh.hexes.len();
meshes.push((b, mesh));
}
// Replace the mesh: definitions stay, nodes, elements and geometry tags are new.
let mut model = s.model.without_mesh();
// Replace the bodies' meshes (replace.rs); other bodies and the definitions stay.
let mut model = s.model.clone();
let cleared = super::replace::clear(&mut model, meshes.iter().map(|(b, _)| b.name.as_str()));
let mut report = Vec::with_capacity(meshes.len());
let (mut node_label, mut element_label) = (1u32, 1u32);
for (b, m) in &meshes {
let first_node = node_label;
for xyz in &m.nodes {
model.set_node(node_label, *xyz)?;
node_label = node_label.checked_add(1).ok_or_else(|| EngineError::Params("too many nodes".into()))?;
let (first_node, first_element) = super::fresh_labels(&model, m.nodes.len(), m.hexes.len())?;
for (i, xyz) in m.nodes.iter().enumerate() {
model.set_node(first_node + i as u32, *xyz)?;
}
let body_tag = model.geometry_tag(&GeometryRef::body(b.name.as_str())?)?;
let first_element = element_label;
for hx in &m.hexes {
model.set_element(element_label, ElementKind::Hex8, hx.iter().map(|&i| first_node + i).collect())?;
model.tag_element(element_label, body_tag)?;
element_label = element_label.checked_add(1).ok_or_else(|| EngineError::Params("too many elements".into()))?;
for (i, hx) in m.hexes.iter().enumerate() {
let l = first_element + i as u32;
model.set_element(l, ElementKind::Hex8, hx.iter().map(|&i| first_node + i).collect())?;
model.tag_element(l, body_tag)?;
}
tag_faces(&mut model, std::slice::from_ref(b), |_| 0, &m.boundary, first_element)?;
let r = &m.report;
@@ -97,8 +97,9 @@ fn hex_octree(s: &mut Session, p: &Value) -> Result<Value> {
"sweeps": r.sweeps,
}));
}
let (nodes, elements) = (model.nodes().len(), model.elements().len());
s.model = model;
Ok(json!({"bodies": report, "nodes": node_label - 1, "elements": element_label - 1}))
Ok(cleared.report(s, json!({"bodies": report, "nodes": nodes, "elements": elements})))
}
#[cfg(test)]
+325
View File
@@ -0,0 +1,325 @@
//! Meshing a body replaces its mesh (#267). Every mesher that fills bodies goes through
//! [`clear`]: before it adds a body's new elements it removes that body's old elements and the
//! nodes only they use, so other bodies keep their meshes and two meshes never stack on one
//! body. The reply's `replaced` says what went; sets that listed the removed labels are named as
//! `stale_sets` (sets by geometry re-resolve on the new mesh), and results solved on the old
//! mesh as `results_cleared`. The command is one undo step, so undo brings the old mesh back.
//!
//! [`MESHERS`] lists those commands with the bodies each one fills, which the UI reads
//! ([`replacement`]) to ask before replacing a mesh. Programmatic calls never ask. `mesh.block`
//! is not one of them: a body is built from several blocks, each call adding one.
use std::collections::{BTreeMap, BTreeSet};
use fieldcraft_model::{BodyMesh, ElementKind, Model};
use serde_json::{Value, json};
use crate::{EngineError, Result, Session};
/// What [`clear`] removed.
#[derive(Default)]
pub(super) struct Cleared {
/// Per body that had a mesh: its name and the element and node counts removed.
bodies: Vec<(String, usize, usize)>,
removed: BodyMesh,
/// Sets that listed a removed node or element by label.
stale_sets: Vec<String>,
}
/// Remove the meshes of `bodies` from `model` (each body once).
pub(super) fn clear<'a>(model: &mut Model, bodies: impl IntoIterator<Item = &'a str>) -> Cleared {
let mut out = Cleared::default();
let mut seen = BTreeSet::new();
for body in bodies {
if !seen.insert(body) {
continue;
}
let r = model.remove_body_mesh(body);
if !r.elements.is_empty() {
out.bodies.push((body.to_string(), r.elements.len(), r.nodes.len()));
out.removed.elements.extend(r.elements);
out.removed.nodes.extend(r.nodes);
}
}
out.stale_sets = model.sets_using(&out.removed);
out
}
impl Cleared {
/// Add `replaced`, `stale_sets` and `results_cleared` to a command's reply (an object).
pub(super) fn report(self, s: &Session, mut reply: Value) -> Value {
if let Some(o) = reply.as_object_mut() {
let replaced: Vec<Value> = self.bodies.iter().map(|(b, e, n)| json!({"body": b, "elements": e, "nodes": n})).collect();
o.insert("replaced".into(), json!(replaced));
if !self.stale_sets.is_empty() {
o.insert("stale_sets".into(), json!(self.stale_sets));
}
let results: Vec<&str> = s.solved_steps().collect();
if !results.is_empty() {
o.insert("results_cleared".into(), json!(results));
}
}
reply
}
}
/// The bodies a meshing command fills, from its parameters, without meshing anything.
pub type Targets = fn(&Session, &Value) -> Result<Vec<String>>;
/// Every command that fills bodies with a mesh and replaces theirs, with the bodies it fills.
pub static MESHERS: &[(&str, Targets)] = &[
("mesh.tet.generate", body_or_all),
("mesh.hex.generate", body_or_all),
("mesh.hex.sweep", body_or_all),
("mesh.hex.mapped", body_or_all),
("mesh.hex.octree", body_or_all),
("mesh.hex.blocks", listed_or_all),
("mesh.cells", listed_or_all),
("mesh.planar", super::mesh::planar_body),
("mesh.mirror", super::mirror::image_names),
];
/// `body`, the imported `surface`, or every body of the open design.
fn body_or_all(s: &Session, p: &Value) -> Result<Vec<String>> {
match (p.get("body"), p.get("surface")) {
(Some(b), None) => Ok(vec![b.as_str().ok_or_else(|| EngineError::param("body", crate::schema::ProblemKind::NotAName))?.to_string()]),
(None, Some(_)) => Ok(vec![super::hex::surface(s, p)?.0]),
(None, None) => design_bodies(s),
_ => Err(EngineError::Params("give `body` or `surface`, not both".into())),
}
}
/// `bodies`, or every body of the open design.
fn listed_or_all(s: &Session, p: &Value) -> Result<Vec<String>> {
match p.get("bodies") {
Some(_) => super::req(p, "bodies"),
None => design_bodies(s),
}
}
fn design_bodies(s: &Session) -> Result<Vec<String>> {
let design = s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first".into()))?;
Ok(design.bodies.iter().map(|b| b.name.clone()).collect())
}
/// What running a meshing command would replace, for a confirmation before it runs.
#[derive(Debug, Clone, PartialEq)]
pub struct Replacement {
/// "CrankArm already has a mesh (7,274 hex20). Replace it?"
pub question: String,
/// What else goes with the old mesh: sets that list its labels, solved results.
pub warnings: Vec<String>,
}
/// What `command` with `params` would replace: `None` when it is not a mesher, its parameters
/// do not name bodies, or none of its bodies has a mesh.
pub fn replacement(s: &Session, command: &str, params: &Value) -> Option<Replacement> {
let targets = MESHERS.iter().find(|(id, _)| *id == command)?.1;
let bodies = targets(s, params).ok()?;
let mut meshed = Vec::new();
let mut removed = BodyMesh::default();
for body in bodies.iter().collect::<BTreeSet<_>>() {
let mesh = s.model.body_mesh(body);
if mesh.elements.is_empty() {
continue;
}
let mut counts: BTreeMap<ElementKind, usize> = BTreeMap::new();
for e in mesh.elements.iter().filter_map(|l| s.model.element(*l)) {
*counts.entry(e.kind).or_default() += 1;
}
let kinds: Vec<String> = ElementKind::ALL.iter().filter_map(|k| counts.get(k).map(|n| format!("{} {}", thousands(*n), k.name()))).collect();
meshed.push((body.as_str(), kinds.join(", ")));
removed.elements.extend(mesh.elements);
removed.nodes.extend(mesh.nodes);
}
let question = match meshed.as_slice() {
[] => return None,
[(body, counts)] => format!("{body} already has a mesh ({counts}). Replace it?"),
many => {
let list: Vec<String> = many.iter().map(|(body, counts)| format!("{body} ({counts})")).collect();
format!("{} already have meshes. Replace them?", list.join(", "))
}
};
let mut warnings = Vec::new();
let stale = s.model.sets_using(&removed);
if !stale.is_empty() {
warnings.push(format!("Sets that list its nodes or elements by label ({}) will name labels of the old mesh.", stale.join(", ")));
}
let results: Vec<&str> = s.solved_steps().collect();
if !results.is_empty() {
warnings.push(format!("The results of {} will be cleared.", results.join(", ")));
}
Some(Replacement { question, warnings })
}
/// `n` with thousands separators: 7274 → "7,274".
fn thousands(n: usize) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
#[cfg(test)]
mod tests {
use fieldcraft_model::Element;
use super::*;
#[test]
fn every_mesher_is_a_command() {
for (id, _) in MESHERS {
assert!(crate::find_command(id).is_some(), "{id}");
}
assert_eq!(thousands(7274), "7,274");
assert_eq!(thousands(999), "999");
assert_eq!(thousands(1_000_000), "1,000,000");
}
/// A 20 × 10 × 10 box split at x = 10 into `Box` (x < 10) and `Box (1)`.
fn two_boxes() -> (crate::tests::TempDir, Session) {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 20, "width": 10, "height": 10, "body_name": "Box"}},
{"command": "solid.split_body", "params": {"body": "Box", "plane": {"origin": [10, 0, 0], "normal": [1, 0, 0]}}},
]});
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
(dir, s)
}
/// A body's elements, by label.
fn elements_of(s: &Session, body: &str) -> BTreeMap<u32, Element> {
s.model.body_elements(body).into_iter().filter_map(|l| Some((l, s.model.element(l)?.clone()))).collect()
}
/// Every mesher in [`MESHERS`], run twice on a body: the second run replaces the first (as
/// many elements as a fresh mesh, reported as `replaced`), leaves the other body's mesh as it
/// was, names the set that listed the old labels, and one undo brings the first mesh back.
#[test]
fn every_mesher_replaces_the_mesh_of_its_body_only() {
let tet_other = json!({"command": "mesh.tet.generate", "params": {"body": "Box (1)", "size": 5}});
let hex_box = json!({"command": "mesh.hex.generate", "params": {"body": "Box", "size": 2.5}});
let square = json!([[0, 0], [10, 0], [10, 10], [0, 10]]);
let cases: Vec<(&str, Vec<Value>, Value, &str, &str)> = vec![
("mesh.tet.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 4}), "Box", "Box (1)"),
("mesh.hex.generate", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.sweep", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.mapped", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.octree", vec![tet_other.clone()], json!({"body": "Box", "size": 2.5}), "Box", "Box (1)"),
("mesh.hex.blocks", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5}), "Box", "Box (1)"),
("mesh.cells", vec![tet_other.clone()], json!({"bodies": ["Box"], "size": 2.5, "default": "hex"}), "Box", "Box (1)"),
("mesh.planar", vec![tet_other.clone()], json!({"polygon": square, "size": 2.5, "name": "Box"}), "Box", "Box (1)"),
// The image's tets (meshed before) are replaced by the mirrored hexahedra.
(
"mesh.mirror",
vec![hex_box, tet_other],
json!({"plane": {"point": [10, 0, 0], "normal": [1, 0, 0]}, "bodies": ["Box"]}),
"Box (1)",
"Box",
),
];
let covered: BTreeSet<&str> = cases.iter().map(|c| c.0).collect();
assert_eq!(covered, MESHERS.iter().map(|m| m.0).collect::<BTreeSet<_>>(), "every mesher has a case");
let (_dir, fresh) = two_boxes();
for (id, prep, params, body, other) in cases {
let mut s = fresh.clone();
for c in &prep {
s.execute(c["command"].as_str().unwrap(), &c["params"]).unwrap();
}
// What the session says it would replace matches what the command replaces.
let first = s.execute(id, &params).unwrap();
let fresh_count = elements_of(&s, body).len();
assert!(fresh_count > 0, "{id}: {first}");
let others = elements_of(&s, other);
assert!(!others.is_empty(), "{id}");
let some: Vec<u32> = elements_of(&s, body).keys().take(3).copied().collect();
s.execute("model.set.create", &json!({"name": "by_label", "elements": some})).unwrap();
let asked = replacement(&s, id, &params).unwrap_or_else(|| panic!("{id}: no question"));
assert!(asked.question.starts_with(&format!("{body} already has a mesh (")), "{id}: {asked:?}");
assert!(asked.warnings.iter().any(|w| w.contains("by_label")), "{id}: {asked:?}");
let before = s.model.clone();
let second = s.execute(id, &params).unwrap();
assert_eq!(elements_of(&s, body).len(), fresh_count, "{id}: {second}");
assert_eq!(elements_of(&s, other), others, "{id}: the other body's mesh is untouched");
assert_eq!(
second["replaced"],
json!([{"body": body, "elements": fresh_count, "nodes": second["replaced"][0]["nodes"]}]),
"{id}: {second}"
);
assert_eq!(second["stale_sets"], json!(["by_label"]), "{id}: {second}");
// No node is left that no element uses.
let used: BTreeSet<u32> = s.model.elements().values().flat_map(|e| e.nodes.iter().copied()).collect();
assert!(s.model.nodes().keys().all(|n| used.contains(n)), "{id}: orphan nodes");
// A mesher is deterministic: the same mesh again is the same model, and no undo step.
if s.model != before {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.model, before, "{id}: undo restores the first mesh");
}
}
}
#[test]
fn tets_over_hexahedra_leave_only_tets() {
let (_dir, mut s) = two_boxes();
s.execute("mesh.hex.generate", &json!({"size": 2.5})).unwrap();
let hexes = elements_of(&s, "Box").len();
let other = elements_of(&s, "Box (1)");
let r = s.execute("mesh.tet.generate", &json!({"body": "Box", "size": 4})).unwrap();
assert_eq!(r["replaced"][0]["elements"], hexes, "{r}");
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Tet4));
assert_eq!(elements_of(&s, "Box (1)"), other);
let tets = s.model.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(elements_of(&s, "Box").len(), hexes, "one undo brings the hexahedra back");
assert!(elements_of(&s, "Box").values().all(|e| e.kind == ElementKind::Hex8));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.model, tets);
// Meshing every body replaces both.
let r = s.execute("mesh.tet.generate", &json!({"size": 4})).unwrap();
assert_eq!(r["replaced"].as_array().map(Vec::len), Some(2), "{r}");
assert!(s.model.elements().values().all(|e| e.kind == ElementKind::Tet4));
// A body without a mesh asks nothing.
let (_dir2, s2) = two_boxes();
assert_eq!(replacement(&s2, "mesh.tet.generate", &json!({"body": "Box"})), None);
assert_eq!(replacement(&s, "mesh.block", &json!({"body": "Box"})), None, "not a mesher");
}
#[test]
fn results_solved_on_the_old_mesh_are_cleared_and_undo_brings_them_back() {
let mut s = Session::default();
let corners = json!([[0, 0, 0], [10, 0, 0], [10, 1, 0], [0, 1, 0], [0, 0, 1], [10, 0, 1], [10, 1, 1], [0, 1, 1]]);
s.run_script(&json!([
{"command": "mesh.block", "params": {"body": "Bar", "kind": "hex8", "corners": corners, "divisions": [10, 1, 1], "faces": {"6": "root", "4": "tip"}}},
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": "Bar"}]}},
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": "Bar", "face": "root"}]}},
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": "Bar", "face": "tip"}]}},
{"command": "model.material.create", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 1000.0, "poisson": 0.0}}},
{"command": "model.section.create", "params": {"name": "all", "set": "all", "material": "Mat", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
{"command": "model.load.create", "params": {"name": "Pull", "type": "force", "target": {"set": "tip"}, "vector": [1, 0, 0]}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Pull"]}}
]))
.unwrap();
s.execute("solve.static", &json!({"step": "Load"})).unwrap();
assert!(s.result("Load").is_some());
let asked = replacement(&s, "mesh.planar", &json!({"polygon": [[0, 0], [10, 0], [10, 1], [0, 1]], "size": 1, "name": "Bar"})).unwrap();
assert_eq!(asked.question, "Bar already has a mesh (10 hex8). Replace it?");
assert!(asked.warnings.iter().any(|w| w.contains("results of Load")), "{asked:?}");
let r = s.execute("mesh.planar", &json!({"polygon": [[0, 0], [10, 0], [10, 1], [0, 1]], "size": 1, "name": "Bar"})).unwrap();
assert_eq!(r["results_cleared"], json!(["Load"]), "{r}");
assert!(s.result("Load").is_none());
assert!(s.model.elements().values().all(|e| e.kind.dimension() == 2));
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.result("Load").is_some(), "undo brings the solved state back");
}
}
+17 -8
View File
@@ -2,9 +2,11 @@
//! animation) and reaction sums. The display is session state ([`ResultsView`]): these
//! commands are not edits, so they are not journalled or undone.
use crate::schema::ProblemKind;
use serde_json::{Value, json};
use super::{opt, xyz};
use crate::requirement::Requirement;
use crate::results::{Field, Kind, MAX_BANDS, MIN_BANDS, ResultsView};
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
@@ -14,15 +16,17 @@ pub const DEFORMED: CommandSpec = CommandSpec {
params: r#"{"step": "Load", "show": true, "scale": "auto"} — shows a solved step's deformed shape (`show: false` the undeformed mesh); `scale` is a factor (0 draws the undeformed shape, so a sequence from 0 swings it out) or "auto" (the largest displacement drawn a tenth of the model's size); `step` defaults to the step shown or the first solved one"#,
form: Some(super::forms::DEFORMED),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: deformed,
};
pub const CONTOUR: CommandSpec = CommandSpec {
id: "results.contour",
label: "Contours",
params: r#"{"step": "Load", "field": "von_mises", "bands": 12} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps); "none" turns them off; 2 to 24 bands"#,
params: r#"{"step": "Load", "field": "von_mises", "bands": 12} — contours of a nodal field: displacement, displacement_x/y/z, von_mises, max/mid/min_principal, stress_xx/yy/zz/xy/xz/yz (stresses for static steps), contact_pressure, contact_gap, contact_status (0 open, 1 closed or stick, 2 slip), contact_shear, contact_slip (friction; nonlinear static steps with contact, at the contacts' secondary surfaces); "none" turns them off; 2 to 24 bands"#,
form: Some(super::forms::CONTOUR),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: contour,
};
@@ -32,6 +36,7 @@ pub const MODES: CommandSpec = CommandSpec {
params: r#"{"step": "Modes", "mode": 1} — shows a mode shape of a solved frequency step (from 1) and lists every mode's frequency"#,
form: Some(super::forms::MODES),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: modes,
};
@@ -41,6 +46,7 @@ pub const ANIMATE: CommandSpec = CommandSpec {
params: r#"{"on": true} — animates the deformed shape: a mode swings through its positive and negative shape, a static step grows from undeformed to deformed"#,
form: Some(super::forms::ANIMATE),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: animate,
};
@@ -50,6 +56,7 @@ pub const FRAME: CommandSpec = CommandSpec {
params: r#"{"step": "Impact", "frame": 3, "time": 0.002} — shows a field frame of a solved explicit step, by index from 0 or the frame nearest a time (neither: the last), or of a nonlinear static step (one per converged increment, `time` its load factor; the deformed shape follows it, its contours show the final state); the deformed shape and contours follow it"#,
form: Some(super::forms::FRAME),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: frame,
};
@@ -59,6 +66,7 @@ pub const REACTIONS: CommandSpec = CommandSpec {
params: r#"{"step": "Load", "sets": ["root"], "about": [0, 0, 0]} — reaction force and moment (about the point) summed over each node set, and over the whole model; `sets` defaults to the sets the step's boundary conditions hold"#,
form: Some(super::forms::REACTIONS),
kind: CommandKind::Session,
requires: &[Requirement::Result],
run: reactions,
};
@@ -68,6 +76,7 @@ pub const CLEAR: CommandSpec = CommandSpec {
params: "{} — back to the model: hides the deformed shape, contours and modes",
form: Some(&[]),
kind: CommandKind::Session,
requires: &[Requirement::ResultsShown],
run: clear,
};
@@ -165,7 +174,7 @@ fn deformed(s: &mut Session, p: &Value) -> Result<Value> {
fn contour(s: &mut Session, p: &Value) -> Result<Value> {
let step = step_for(s, p, Want::Any)?;
let name = opt::<String>(p, "field")?.ok_or_else(|| EngineError::Params("`field` is required (a field id, or \"none\")".into()))?;
let name = opt::<String>(p, "field")?.ok_or_else(|| EngineError::param("field", ProblemKind::Required))?;
let field = match name.as_str() {
"none" => None,
id => Some(Field::parse(id).ok_or_else(|| {
@@ -247,7 +256,7 @@ fn frame(s: &mut Session, p: &Value) -> Result<Value> {
(None, Some(t)) if t.is_finite() => {
times.iter().enumerate().min_by(|a, b| (a.1 - t).abs().total_cmp(&(b.1 - t).abs())).map_or(last, |(i, _)| i)
}
(None, Some(_)) => return Err(EngineError::Params("`time` must be a number".into())),
(None, Some(_)) => return Err(EngineError::param("time", ProblemKind::NotANumber)),
(None, None) => last,
};
let v = view_of(s, &step)?;
@@ -264,7 +273,7 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
let step = step_for(s, p, Want::Any)?;
let about = if p.get("about").is_some() { xyz(p, "about")? } else { [0.0; 3] };
if !about.iter().all(|c| c.is_finite()) {
return Err(EngineError::Params("`about` must be a finite [x, y, z]".into()));
return Err(EngineError::param("about", ProblemKind::NotAVector { len: 3 }));
}
let Some((result, current)) = s.latest_result(&step) else { return Err(EngineError::Params(solved_list(s))) };
let Kind::Static(r) = result.kind() else {
@@ -279,7 +288,7 @@ fn reactions(s: &mut Session, p: &Value) -> Result<Value> {
.filter(|a| a.len() <= MAX_SETS)
.ok_or_else(|| EngineError::Params(format!("`sets` must be a list of at most {MAX_SETS} set names")))?;
list.iter()
.map(|n| n.as_str().map(str::to_string).ok_or_else(|| EngineError::Params("`sets` must be set names".into())))
.map(|n| n.as_str().map(str::to_string).ok_or_else(|| EngineError::param("sets", ProblemKind::NotNames)))
.collect::<Result<_>>()?
}
None => {
@@ -338,8 +347,8 @@ mod tests {
fn the_display_follows_the_commands_and_is_not_an_edit() {
let mut s = solved();
let (journal, revision) = (s.journal.len(), s.revision());
// Solving showed the first solved step.
assert_eq!(s.results_view.as_ref().map(|v| (v.step.as_str(), v.contour)), Some(("Bend", Some(Field::VonMises))));
// Solving showed the first solved step, a static one: contours on the undeformed shape.
assert_eq!(s.results_view.as_ref().map(|v| (v.step.as_str(), v.contour, v.deformed)), Some(("Bend", Some(Field::VonMises), false)));
s.execute("results.clear", &json!({})).unwrap();
let r = s.execute("results.contour", &json!({"field": "von_mises"})).unwrap();
assert_eq!(r["view"]["step"], "Bend", "{r}");
@@ -356,7 +365,7 @@ mod tests {
let r = s.execute("results.modes", &json!({"mode": 3})).unwrap();
assert_eq!((r["view"]["step"].as_str(), r["view"]["mode"].as_u64()), (Some("Modes"), Some(3)));
assert_eq!(r["modes"].as_array().map(Vec::len), Some(4));
assert_eq!(s.results_view.as_ref().and_then(|v| v.contour), Some(Field::Displacement));
assert_eq!(s.results_view.as_ref().map(|v| (v.contour, v.deformed)), Some((Some(Field::Displacement), true)), "a mode shape is deformed");
assert!(s.execute("results.contour", &json!({"field": "von_mises"})).is_err());
s.execute("results.contour", &json!({"field": "displacement", "bands": 6})).unwrap();
s.execute("results.animate", &json!({})).unwrap();
+325
View File
@@ -0,0 +1,325 @@
//! Edge seeds: `mesh.seed.edge` sets a count or a size (with bias and constraint) on design
//! edges, `mesh.seed.clear` removes seeds and `mesh.seed.list` lists them with the count each
//! gives on its edge. Seeds live in the model (`fieldcraft_model::seeds`), are saved with it, and
//! the meshers honour them.
use fieldcraft_geometry::{Design, Edge};
use fieldcraft_model::{Bias, Divisions, Entity, GeometryRef, Seed, SeedConstraint};
use serde_json::{Value, json};
use super::opt;
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
/// Most edges one command names.
const MAX_EDGES: usize = 10_000;
pub const SEED_EDGE: CommandSpec = CommandSpec {
id: "mesh.seed.edge",
label: "Seed Edges",
params: r#"{"edges": [{"body": "Body1", "edge": "F2:side:hi|F2:top"}, …], "count": 8 | "size": 2.5, "bias"?: {"ratio": 4, "toward": "start" | "end" | "both"}, "constraint"?: "exact" (default) | "min" | "free"} — seeds design edges (persistent edge names, geometry.bodies): `count` divisions, or `size` (the edge's length over it, rounded up). `bias` grades the elements geometrically, the largest `ratio` times the smallest, small at the edge's start, end or both ends. `constraint`: "exact" keeps the count (a mesher whose other edges cannot match refuses, naming the conflicting edges), "min" keeps at least it, "free" makes it a goal. Replaces a seed the edge had; an edge name without its `~k` number seeds every edge of that name. The hex meshers (sweep, mapped, blocks, cells) use the counts and spacing; the tet mesher uses the spacing on the edge and grades its size field from it"#,
form: Some(super::forms::SEED_EDGE),
kind: CommandKind::Model,
requires: &[Requirement::Design],
run: seed_edge,
};
pub const SEED_CLEAR: CommandSpec = CommandSpec {
id: "mesh.seed.clear",
label: "Clear Seeds",
params: r#"{"edges"?: [{"body", "edge"}, …]} — removes the seeds on these edges (by the names they were seeded with), or every seed"#,
form: Some(super::forms::SEED_CLEAR),
kind: CommandKind::Model,
requires: &[Requirement::Seed],
run: seed_clear,
};
pub const SEED_LIST: CommandSpec = CommandSpec {
id: "mesh.seed.list",
label: "Seeds",
params: "{} — the edge seeds, each with the edges of the open design it seeds, their lengths and the count it gives each (`stale`: the design has no such edge)",
form: Some(&[]),
kind: CommandKind::Model,
requires: &[],
run: seed_list,
};
/// The `edges` parameter: a list of edge references.
fn edge_refs(p: &Value, required: bool) -> Result<Option<Vec<GeometryRef>>> {
let refs: Option<Vec<GeometryRef>> = opt(p, "edges")?;
let Some(refs) = refs else {
return if required { Err(EngineError::Params("`edges` is required: a list of {body, edge}".into())) } else { Ok(None) };
};
if refs.is_empty() || refs.len() > MAX_EDGES {
return Err(EngineError::Params(format!("`edges` must list 1 to {MAX_EDGES} edges")));
}
if let Some(r) = refs.iter().find(|r| !matches!(r.entity, Entity::Edge(_))) {
return Err(EngineError::Params(format!("`edges` lists the {r}; name edges as {{body, edge}}")));
}
Ok(Some(refs))
}
/// The edges of the design a reference selects (its `~k` pieces too).
pub(crate) fn seeded_edges(design: &Design, r: &GeometryRef) -> Result<Vec<Edge>> {
let Some(body) = design.body(&r.body) else { return Ok(Vec::new()) };
Ok(body.edges()?.into_iter().filter(|e| GeometryRef::new(r.body.clone(), Entity::Edge(e.name.clone())).is_ok_and(|g| r.selects(&g))).collect())
}
/// Every seed on the open design's edges, as the meshers take them. A mesher matches them to its
/// own curves by position, so a seed on an edge two partition cells share holds in both.
pub(crate) fn edge_seeds(s: &Session) -> Result<Vec<fieldcraft_mesh::seeds::EdgeSeed>> {
let Some(design) = s.design.as_deref() else { return Ok(Vec::new()) };
let mut out = Vec::new();
// Each body's edges, found once.
let mut edges: std::collections::BTreeMap<&str, (f64, Vec<Edge>)> = std::collections::BTreeMap::new();
for seed in s.model.seeds() {
let Some(body) = design.body(&seed.edge.body) else { continue };
let (tolerance, all) = match edges.entry(body.name.as_str()) {
std::collections::btree_map::Entry::Occupied(e) => e.into_mut(),
std::collections::btree_map::Entry::Vacant(v) => {
v.insert(((body.size()? * fieldcraft_geometry::EDGE_TOLERANCE).max(1e-4), body.edges()?))
}
};
let selected = all.iter().filter(|e| GeometryRef::new(body.name.clone(), Entity::Edge(e.name.clone())).is_ok_and(|g| seed.edge.selects(&g)));
for e in selected.cloned().collect::<Vec<_>>() {
let tolerance = *tolerance;
out.push(fieldcraft_mesh::seeds::EdgeSeed {
name: format!("{}:{}", seed.edge.body, e.name),
count: seed.count(e.length()) as usize,
points: e.points,
tolerance,
bias: seed.bias,
constraint: seed.constraint,
});
}
}
Ok(out)
}
fn design(s: &Session) -> Result<&Design> {
s.design.as_deref().ok_or_else(|| EngineError::Params("open a design first (geometry.open)".into()))
}
/// A seed's report: its definition and, per edge it seeds, the length and the count it gives.
fn report(seed: &Seed, edges: &[Edge]) -> Value {
let mut v = json!(seed);
v["on"] = edges.iter().map(|e| json!({"edge": e.name, "length": e.length(), "count": seed.count(e.length())})).collect();
v["stale"] = json!(edges.is_empty());
v
}
fn seed_edge(s: &mut Session, p: &Value) -> Result<Value> {
let refs = edge_refs(p, true)?.unwrap_or_default();
let divisions = match (opt::<u32>(p, "count")?, opt::<f64>(p, "size")?) {
(Some(n), None) => Divisions::Count(n),
(None, Some(h)) => Divisions::Size(h),
_ => return Err(EngineError::Params("give one of `count` (divisions) or `size` (element length)".into())),
};
let bias: Option<Bias> = opt(p, "bias")?;
let constraint: SeedConstraint = opt(p, "constraint")?.unwrap_or_default();
let design = design(s)?.clone();
let mut out = Vec::with_capacity(refs.len());
for r in refs {
let edges = seeded_edges(&design, &r)?;
if edges.is_empty() {
return Err(EngineError::Params(format!("the design has no {r} (geometry.bodies lists the edges)")));
}
let seed = Seed::new(r, divisions, bias, constraint)?;
out.push(report(&seed, &edges));
s.model.set_seed(seed)?;
}
Ok(json!({"seeded": out.len(), "seeds": out}))
}
fn seed_clear(s: &mut Session, p: &Value) -> Result<Value> {
let cleared = match edge_refs(p, false)? {
None => s.model.clear_seeds(),
Some(refs) => {
if let Some(r) = refs.iter().find(|r| s.model.seed(r).is_none()) {
return Err(EngineError::Params(format!("the {r} has no seed")));
}
refs.iter().filter(|r| s.model.remove_seed(r)).count()
}
};
Ok(json!({"cleared": cleared, "left": s.model.seeds().len()}))
}
fn seed_list(s: &mut Session, _: &Value) -> Result<Value> {
let mut out = Vec::with_capacity(s.model.seeds().len());
for seed in s.model.seeds() {
let edges = match s.design.as_deref() {
Some(d) => seeded_edges(d, &seed.edge)?,
None => Vec::new(),
};
out.push(report(seed, &edges));
}
Ok(Value::Array(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn plate() -> Session {
super::super::datum::tests::plate().0
}
fn thickness_edges(s: &mut Session) -> Vec<Value> {
let bodies = s.execute("geometry.bodies", &json!({})).unwrap();
bodies[0]["edges"]
.as_array()
.unwrap()
.iter()
.filter(|e| (e["length"].as_f64().unwrap() - 10.0).abs() < 1e-6)
.map(|e| json!({"body": "Body1", "edge": e["name"]}))
.collect()
}
#[test]
fn seeds_are_set_replaced_listed_cleared_and_undone() {
let mut s = plate();
let edges = thickness_edges(&mut s);
let r = s.execute("mesh.seed.edge", &json!({"edges": edges[..2], "count": 4, "bias": {"ratio": 3, "toward": "end"}})).unwrap();
assert_eq!(r["seeded"], 2);
assert_eq!(r["seeds"][0]["on"][0]["count"], 4);
assert_eq!(r["seeds"][0]["constraint"], "exact");
// A size gives the length over it, rounded up; it replaces the count.
let r = s.execute("mesh.seed.edge", &json!({"edges": [edges[0]], "size": 3.0, "constraint": "min"})).unwrap();
assert_eq!(r["seeds"][0]["on"][0]["count"], 4);
assert_eq!(s.model.seeds().len(), 2);
let list = s.execute("mesh.seed.list", &json!({})).unwrap();
assert_eq!(list.as_array().unwrap().len(), 2);
assert!(list.as_array().unwrap().iter().all(|l| l["stale"] == false));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.model.seed(&serde_json::from_value(edges[0].clone()).unwrap()).unwrap().divisions, Divisions::Count(4));
s.execute("mesh.seed.clear", &json!({"edges": [edges[1]]})).unwrap();
assert_eq!(s.model.seeds().len(), 1);
assert!(s.execute("mesh.seed.clear", &json!({"edges": [edges[1]]})).is_err());
assert_eq!(s.execute("mesh.seed.clear", &json!({})).unwrap()["cleared"], 1);
assert!(s.execute("mesh.seed.clear", &json!({})).is_err(), "nothing to clear");
}
#[test]
fn seeds_survive_save_open_and_a_design_edit() {
let (mut s, dir) = super::super::datum::tests::plate();
let edges = thickness_edges(&mut s);
s.execute("mesh.seed.edge", &json!({"edges": edges, "count": 5, "bias": {"ratio": 2, "toward": "both"}})).unwrap();
let file = dir.join("seeded.fieldcraft");
s.execute("file.save", &json!({"path": file.to_str().unwrap()})).unwrap();
let mut back = Session::default();
back.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
assert_eq!(back.model.seeds(), s.model.seeds());
// The plate made thicker: the same edges, now 15 mm, keep their seeds.
let design = dir.join("plate.solidcraft");
let thick = fieldcraft_geometry::sample::Plate { thickness: 15.0, ..Default::default() };
std::fs::write(&design, fieldcraft_geometry::sample::plate_design(&thick).unwrap()).unwrap();
let r = back.execute("geometry.open", &json!({"path": design.to_str().unwrap()})).unwrap();
assert_eq!(r["stale"]["seeds"], json!([]));
let list = back.execute("mesh.seed.list", &json!({})).unwrap();
for l in list.as_array().unwrap() {
assert_eq!(l["on"].as_array().unwrap().len(), 1, "{l}");
assert!((l["on"][0]["length"].as_f64().unwrap() - 15.0).abs() < 1e-6, "{l}");
}
}
/// The polyline of edge `name` of body `body`.
fn edge_points(s: &Session, body: &str, name: &str) -> Vec<[f64; 3]> {
s.design.as_ref().unwrap().body(body).unwrap().edges().unwrap().into_iter().find(|e| e.name == name).unwrap().points
}
/// The model's nodes on a straight edge, by their distance from its start, sorted.
fn nodes_on(s: &Session, line: &[[f64; 3]]) -> Vec<f64> {
let (a, b) = (line[0], *line.last().unwrap());
let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let mut out: Vec<f64> = s
.model
.nodes()
.values()
.filter_map(|n| {
let v = [n.xyz[0] - a[0], n.xyz[1] - a[1], n.xyz[2] - a[2]];
let t = (v[0] * d[0] + v[1] * d[1] + v[2] * d[2]) / len;
let off = [v[0] - t * d[0] / len, v[1] - t * d[1] / len, v[2] - t * d[2] / len];
let off = (off[0] * off[0] + off[1] * off[1] + off[2] * off[2]).sqrt();
(off < 1e-6 && (-1e-6..=len + 1e-6).contains(&t)).then_some(t)
})
.collect();
out.sort_by(f64::total_cmp);
out
}
#[test]
fn the_meshers_honour_seeds() {
let mut s = plate();
let edges = thickness_edges(&mut s);
let name = edges[0]["edge"].as_str().unwrap().to_string();
let line = edge_points(&s, "Body1", &name);
let seed = json!({"edges": [edges[0]], "count": 5, "bias": {"ratio": 3, "toward": "end"}});
s.execute("mesh.seed.edge", &seed).unwrap();
// Hex sweep: five layers through the thickness, graded geometrically toward the edge's end.
s.execute("mesh.hex.sweep", &json!({"body": "Body1", "size": 4})).unwrap();
let t = nodes_on(&s, &line);
let dt: Vec<f64> = t.windows(2).map(|w| w[1] - w[0]).collect();
assert_eq!(dt.len(), 5, "{t:?}");
assert!((dt[0] / dt[4] - 3.0).abs() < 1e-6, "{dt:?}");
// Tet: the edge is divided at the seed's nodes.
let r = s.execute("mesh.tet.generate", &json!({"body": "Body1", "size": 5})).unwrap();
assert_eq!(r["bodies"][0]["seeds"][0]["mesh_edges"], 5, "{}", r["bodies"][0]["seeds"]);
// Two exact seeds that cannot both hold are refused, naming both.
s.execute("mesh.seed.edge", &json!({"edges": [edges[1]], "count": 3})).unwrap();
let e = s.execute("mesh.hex.sweep", &json!({"body": "Body1", "size": 4})).unwrap_err().to_string();
assert!(e.contains(&name) && e.contains(edges[1]["edge"].as_str().unwrap()) && e.contains("conflict"), "{e}");
}
#[test]
fn a_seed_on_a_cut_edge_holds_in_both_cells() {
let (mut s, _dir) = super::super::datum::tests::plate();
s.execute("geometry.datum", &json!({"name": "X30", "by": {"type": "offset", "plane": "yz", "offset": 30}})).unwrap();
s.execute("geometry.partition", &json!({"name": "P", "datum": "X30"})).unwrap();
// An edge of the cut face, 30 mm along y, on the cell with the hole.
let edge = s
.design
.as_ref()
.unwrap()
.body("Body1/a")
.unwrap()
.edges()
.unwrap()
.into_iter()
.find(|e| e.name.contains("partition:P:a") && (e.length() - 30.0).abs() < 1e-6)
.unwrap();
s.execute("mesh.seed.edge", &json!({"edges": [{"body": "Body1/a", "edge": edge.name}], "count": 9})).unwrap();
let r = s.execute("mesh.cells", &json!({"default": "hex", "size": 2.5})).unwrap();
assert_eq!(r["interfaces"][0]["joined"], "merged", "{r}");
assert_eq!(nodes_on(&s, &edge.points).len(), 10, "{r}");
}
#[test]
fn hostile_seeds_are_refused_and_change_nothing() {
let mut s = plate();
let edges = thickness_edges(&mut s);
let e = edges[0].clone();
for p in [
json!({}),
json!({"edges": [], "count": 2}),
json!({"edges": [e], "count": 2, "size": 1.0}),
json!({"edges": [e]}),
json!({"edges": [e], "count": 0}),
json!({"edges": [e], "count": -3}),
json!({"edges": [e], "count": 1e12}),
json!({"edges": [e], "size": 0.0}),
json!({"edges": [e], "count": 2, "bias": {"ratio": 1e9, "toward": "end"}}),
json!({"edges": [e], "count": 2, "bias": {"ratio": 2, "toward": "middle"}}),
json!({"edges": [e], "count": 2, "constraint": "loose"}),
json!({"edges": [{"body": "Body1", "face": "x"}], "count": 2}),
json!({"edges": [{"body": "Body1", "edge": "no|such"}], "count": 2}),
json!({"edges": [{"body": "Nope", "edge": "a|b"}], "count": 2}),
json!({"edges": "all", "count": 2}),
] {
assert!(s.execute("mesh.seed.edge", &p).is_err(), "{p}");
}
assert!(s.model.seeds().is_empty());
assert!(s.journal.is_empty() || s.journal.iter().all(|(c, _)| c != "mesh.seed.edge"));
}
}
+139 -15
View File
@@ -1,6 +1,7 @@
//! `solve.*`: run the model's steps with the implicit, the explicit or the lattice Boltzmann
//! solver, keep the results in the session, and read them back.
use crate::schema::ProblemKind;
use fieldcraft_explicit::{ExplicitResult, solve_explicit};
use fieldcraft_lbm::{FluidResult, Obstacle};
use fieldcraft_mesh::surface::{BoundarySurface, SurfaceOptions};
@@ -13,6 +14,7 @@ use fieldcraft_solver::{
use serde_json::{Value, json};
use super::{labels, opt, points, req};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session, StepResult};
pub const RUN: CommandSpec = CommandSpec {
@@ -21,6 +23,7 @@ pub const RUN: CommandSpec = CommandSpec {
params: r#"{} — solves every step in order with its procedure's solver (solve.static, solve.frequency, solve.explicit, solve.fluid with their default caps) and keeps the results; stops at the first step that fails, naming it"#,
form: Some(&[]),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_all,
};
@@ -30,15 +33,17 @@ pub const STATIC: CommandSpec = CommandSpec {
params: r#"{"step": "Load", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — solves a linear static or coupled temperature–displacement step (the only one when `step` is left out) and keeps the result in the session; the caps may only be lowered; `threads` (1 to 256, by default the session's: `FIELDCRAFT_THREADS` or the cores) changes only the time, never the result"#,
form: Some(super::forms::SOLVE_STATIC),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_static,
};
pub const NONLINEAR: CommandSpec = CommandSpec {
id: "solve.nonlinear",
label: "Solve Nonlinear Static Step",
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment; the caps may only be lowered (`max_newton_iterations` over the whole step); `threads` as for solve.static"#,
params: r#"{"step": "Inflate", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_newton_iterations": 100000, "threads": 8} — solves a nonlinear static step (the only one when `step` is left out) in load increments with Newton–Raphson iterations and keeps the result in the session: the final displacements, reactions, Cauchy stresses and logarithmic strains (small strains without nonlinear geometry), the equivalent plastic strain of plastic materials (the largest in the summary), every increment's load factor, iterations and residuals (force, displacement and energy, relative to their tolerances' scales), and a displacement frame per converged increment, and with contact pairs (interaction.contact.pair: mortar contact by augmented Lagrangian, Coulomb friction by a return map) each contact's force, normal force, largest pressure, closed and slipping nodes, deepest penetration and augmentations (solve.probe gives each secondary node's pressure, gap and status, and with friction its shear traction and slip); the caps may only be lowered (`max_newton_iterations` over the whole step); `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_NONLINEAR),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_nonlinear,
};
@@ -48,6 +53,7 @@ pub const HEAT: CommandSpec = CommandSpec {
params: r#"{"step": "Heat", "max_dofs": 6000000, "max_factor_entries": 400000000, "threads": 8} — steady or transient heat conduction of a heat transfer step (the only one when `step` is left out): temperatures, heat flux and the heat flow at prescribed temperatures, kept in the session; the caps may only be lowered; `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_STATIC),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_heat,
};
@@ -57,6 +63,7 @@ pub const FREQUENCY: CommandSpec = CommandSpec {
params: r#"{"step": "Modes", "mass": "consistent|lumped", "shift": 0.0, "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — natural frequencies and mode shapes of a frequency step (its modes and range); `max_iterations` caps the Lanczos vectors; the result stays in the session; `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_FREQUENCY),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_frequency,
};
@@ -66,6 +73,7 @@ pub const BUCKLE: CommandSpec = CommandSpec {
params: r#"{"step": "Buckle", "max_dofs": 6000000, "max_factor_entries": 400000000, "max_iterations": 3000, "threads": 8} — linear buckling of a buckling step (the only one when `step` is left out): the step's loads as a linear preload, then the lowest load factors λ with (K + λ K_σ) φ = 0 and their mode shapes (largest component 1), or those above the step's shift (whose LDLᵀ factor counts the load factors below it); negative load factors found are reported; the result stays in the session and its modes display like frequency modes; `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_BUCKLE),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_buckle,
};
@@ -75,6 +83,7 @@ pub const EXPLICIT: CommandSpec = CommandSpec {
params: r#"{"step": "Impact", "max_dofs": 6000000, "max_increments": 1000000000, "max_output_values": 50000000, "max_contact_faces": 10000000, "threads": 8} — transient response of an explicit dynamic step (the only one when `step` is left out) by central differences, with the model's contacts (interaction.contact.*) and the step's rigid walls; keeps its histories and field frames in the session and reports each contact's peak force, first and last contact, deepest penetration, friction dissipated and the nodes adjusted at the start; the caps may only be lowered (the step's own increment cap applies too); `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_EXPLICIT),
kind: CommandKind::Model,
requires: &[Requirement::Analysable, Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step],
run: run_explicit,
};
@@ -84,6 +93,7 @@ pub const HISTORY: CommandSpec = CommandSpec {
params: r#"{"step": "Impact", "every": 1} — the time histories of a solved explicit step: time, increment, energies, momentum, constraint force, the normal force across each contact (in `contacts` order) and the history nodes' displacement and velocity; `every` keeps one sample in so many (by default enough to return at most 10000)"#,
form: Some(super::forms::SOLVE_HISTORY),
kind: CommandKind::Model,
requires: &[Requirement::Result],
run: history,
};
@@ -93,6 +103,7 @@ pub const FLUID: CommandSpec = CommandSpec {
params: r#"{"step": "Flow", "max_cells": 16000000, "max_steps": 10000000, "max_cell_updates": 1e12, "max_frame_bytes": 2e9, "threads": 8} — runs a fluid step with the lattice Boltzmann solver (the only fluid step when `step` is left out): obstacles are triangulated from the open design or taken from imported surfaces; returns the time step, relaxation time, Mach number, mass and the final force on every wall; the caps may only be lowered; `threads` as for solve.static"#,
form: Some(super::forms::SOLVE_FLUID),
kind: CommandKind::Model,
requires: &[Requirement::FluidDomain, Requirement::Step],
run: run_fluid,
};
@@ -102,6 +113,7 @@ pub const PROBE: CommandSpec = CommandSpec {
params: r#"{"step": "Load", "nodes": [1, 2] (or "set": "fillet", a set's nodes), "mode": 1, "frame": 0} — the stored result at nodes (with `max_von_mises`, the largest among them, for static steps): displacement, rotation, reaction, reaction moment, stress and von Mises (static, with `elements` each element's results: solid, 2D and truss nodal stresses (and, in a nonlinear step, the equivalent plastic strain at the integration points of a plastic element), shell section forces (N, M, Q per length in the element's axes) and bottom, middle and top stresses, beam end forces (N, V_y, V_z, T, M_y, M_z in its axes)), the shape of mode `mode` with its rotations (frequency, from 1), or displacement and velocity in field frame `frame` (explicit, from 0; the last by default) at `nodes` (or at the nodes nearest to points: "at": [[x, y, z], ...], lowest label on a tie, each entry then giving its `xyz` and `distance`) and, with `elements` (explicit), each element's stress, von Mises stress, strain, equivalent plastic strain, damage, temperature and whether it has eroded; a coupled reference point's label gives its six displacements (translations, rotations) and reactions (forces, moments). Fluid steps: {"step": "Flow", "points": [[x, y, z]], "frame": 10 (default the last)} gives velocity and pressure in the cells at the points; {"step": "Flow", "forces": ["x_min", "F2:top", "Body1/F2:top"]} gives those walls' force histories"#,
form: Some(super::forms::SOLVE_PROBE),
kind: CommandKind::Model,
requires: &[Requirement::Result],
run: probe,
};
@@ -123,7 +135,7 @@ fn cap<T: Copy + TryInto<u64> + TryFrom<u64> + std::fmt::Display>(p: &Value, key
.as_u64()
.filter(|n| (1..=most).contains(n))
.and_then(|n| T::try_from(n).ok())
.ok_or_else(|| EngineError::Params(format!("`{key}` must be a whole number from 1 to {default}"))),
.ok_or_else(|| EngineError::param(key, ProblemKind::NotAWholeNumber { min: 1, max: i64::try_from(most).unwrap_or(i64::MAX) })),
}
}
@@ -239,6 +251,16 @@ fn run_nonlinear(s: &mut Session, p: &Value) -> Result<Value> {
"frames": history.map(|h| h.load_factors()),
"load_factor": history.and_then(|h| h.frames.last()).map(|f| f.load_factor),
"critical_points": history.map(|h| &h.critical_points),
"contacts": r.contacts.iter().map(|c| json!({
"name": c.name,
"normal_force": c.normal_force,
"force": c.force,
"max_pressure": largest(c.nodes.iter().copied().zip(c.pressure.iter().copied())),
"closed_nodes": c.closed(),
"slipping_nodes": c.status.iter().filter(|s| **s == fieldcraft_solver::contact::Status::Slip).count(),
"penetration": c.penetration,
"augmentations": c.augmentations,
})).collect::<Vec<_>>(),
"max_displacement": largest(r.nodes.iter().zip(&r.displacement).map(|(l, u)| (*l, crate::results::magnitude(*u)))),
"max_von_mises": largest(r.nodes.iter().zip(&r.von_mises).map(|(l, v)| (*l, *v))),
"max_plastic_strain": largest(r.elements.iter().flat_map(|e| e.plastic_strain.iter().map(|v| (e.label, *v)))),
@@ -369,7 +391,7 @@ fn history(s: &mut Session, p: &Value) -> Result<Value> {
let h = &r.history;
let samples = h.time.len();
let every = match opt::<u64>(p, "every")? {
Some(0) => return Err(EngineError::Params("`every` must be at least 1".into())),
Some(0) => return Err(EngineError::param("every", ProblemKind::Below(1.0))),
Some(k) => usize::try_from(k).unwrap_or(usize::MAX),
None => samples.div_ceil(MAX_HISTORY_SAMPLES).max(1),
};
@@ -520,7 +542,7 @@ fn probe_fluid(r: &FluidResult, p: &Value) -> Result<Value> {
}
fn probe(s: &mut Session, p: &Value) -> Result<Value> {
let step = opt::<String>(p, "step")?.ok_or_else(|| EngineError::Params("`step` is required".into()))?;
let step = opt::<String>(p, "step")?.ok_or_else(|| EngineError::param("step", ProblemKind::Required))?;
let result = s.result(&step).ok_or_else(|| {
EngineError::Params(if s.latest_result(&step).is_some() {
format!("the result of step `{step}` is stale (the model changed since it was solved); solve it again")
@@ -609,16 +631,36 @@ fn probe_implicit(result: &ImplicitResult, step: &str, nodes: &[u32], p: &Value)
let p = r.reference_points.get(k);
json!({"node": l, "reference_point": p.map(|p| &p.name), "displacement": p.map(|p| p.displacement), "reaction": p.map(|p| p.reaction)})
}
Location::Node(i) => json!({
"node": l,
"displacement": r.displacement.get(i),
"rotation": r.rotation.get(i),
"reaction": r.reaction.get(i),
"reaction_moment": r.reaction_moment.get(i),
"stress": r.stress.get(i),
"von_mises": r.von_mises.get(i),
"temperature": r.temperature.as_ref().and_then(|t| t.get(i)),
}),
Location::Node(i) => {
let mut v = json!({
"node": l,
"displacement": r.displacement.get(i),
"rotation": r.rotation.get(i),
"reaction": r.reaction.get(i),
"reaction_moment": r.reaction_moment.get(i),
"stress": r.stress.get(i),
"von_mises": r.von_mises.get(i),
"temperature": r.temperature.as_ref().and_then(|t| t.get(i)),
});
// The contacts the node is a secondary node of: pressure, gap, status.
let contact: Vec<Value> = r
.contacts
.iter()
.filter_map(|c| {
let k = c.nodes.binary_search(&l).ok()?;
let mut entry = json!({"contact": c.name, "pressure": c.pressure.get(k), "gap": c.gap.get(k), "status": c.status.get(k)});
if let (Some(shear), Some(slip)) = (c.shear.get(k), c.slip.get(k)) {
entry["shear"] = json!(shear);
entry["slip"] = json!(slip);
}
Some(entry)
})
.collect();
if !contact.is_empty() {
v["contact"] = Value::Array(contact);
}
v
}
})
})
.collect::<Result<_>>()?,
@@ -762,7 +804,7 @@ pub(crate) mod tests {
s.execute("solve.run", &json!({})).unwrap();
assert!(s.result("Impact").is_some());
let mut empty = Session::default();
assert!(empty.execute("solve.run", &json!({})).unwrap_err().to_string().contains("no steps"));
assert!(empty.execute("solve.run", &json!({})).unwrap_err().to_string().contains("Needs a mesh"));
}
use super::*;
@@ -1509,4 +1551,86 @@ pub(crate) mod tests {
let all = s.execute("solve.run", &json!({})).unwrap();
assert_eq!(all["steps"].as_array().map(Vec::len), Some(3), "{all}");
}
/// Two blocks pressed together across a contact pair, as commands.
fn pressed_blocks(s: &mut Session) {
let script = json!([
{"command": "mesh.block", "params": {"body": "Lower", "kind": "hex8", "corners": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]], "divisions": [2, 2, 1], "faces": {"1": "bottom", "2": "top"}}},
{"command": "mesh.block", "params": {"body": "Upper", "kind": "hex8", "corners": [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1], [0, 0, 2], [1, 0, 2], [1, 1, 2], [0, 1, 2]], "divisions": [3, 3, 1], "faces": {"1": "bottom", "2": "top"}, "merge": 0}},
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": "Lower"}, {"body": "Upper"}]}},
{"command": "model.set.create", "params": {"name": "lower_top", "geometry": [{"body": "Lower", "face": "top"}]}},
{"command": "model.set.create", "params": {"name": "upper_bottom", "geometry": [{"body": "Upper", "face": "bottom"}]}},
{"command": "model.set.create", "params": {"name": "base", "geometry": [{"body": "Lower", "face": "bottom"}]}},
{"command": "model.set.create", "params": {"name": "top", "geometry": [{"body": "Upper", "face": "top"}]}},
{"command": "model.material.create", "params": {"name": "Mat", "elastic": {"type": "isotropic", "young": 1000.0, "poisson": 0.0}}},
{"command": "model.section.create", "params": {"name": "all", "set": "all", "material": "Mat", "kind": {"type": "solid"}}},
{"command": "interaction.contact.pair", "params": {"name": "interface", "main": "lower_top", "secondary": "upper_bottom"}},
{"command": "model.boundary_condition.create", "params": {"name": "base", "type": "fixed", "target": {"set": "base"}}},
{"command": "model.boundary_condition.create", "params": {"name": "push", "type": "displacement", "target": {"set": "top"}, "values": [0, 0, -0.02, null, null, null]}},
{"command": "model.step.create", "params": {"name": "Squeeze", "procedure": {"type": "nonlinear_static", "nonlinear_geometry": false}, "boundary_conditions": ["base", "push"], "loads": []}}
]);
s.run_script(&script).unwrap();
}
#[test]
fn solve_and_probe_a_contact() {
let mut s = Session::default();
pressed_blocks(&mut s);
let r = s.execute("solve.nonlinear", &json!({"step": "Squeeze"})).unwrap();
let c = &r["contacts"][0];
assert_eq!(c["name"], "interface");
// ν = 0 and held ends: uniaxial strain 1% of E = 1000, over the unit area.
let force = c["normal_force"].as_f64().unwrap();
assert!((force - 10.0).abs() < 2e-3, "{r}");
assert_eq!(c["closed_nodes"], 16, "{r}");
// A secondary node gives its contact pressure, gap and status; a main one gives none.
let third = 1.0 / 3.0;
let probe = s.execute("solve.probe", &json!({"step": "Squeeze", "at": [[third, third, 1.0], [0.5, 0.5, 1.0]]})).unwrap();
let contact = &probe["nodes"][0]["contact"][0];
assert_eq!(contact["status"], "closed", "{probe}");
assert!((contact["pressure"].as_f64().unwrap() - 10.0).abs() < 2e-3, "{probe}");
assert!(contact["gap"].as_f64().unwrap() < 0.0, "{probe}");
assert!(probe["nodes"][1].get("contact").is_none(), "{probe}");
// The contact fields on the results display.
let v = s.execute("results.contour", &json!({"step": "Squeeze", "field": "contact_pressure"})).unwrap();
let range = &v["contour"]["range"];
assert!((range["max"]["value"].as_f64().unwrap() - 10.0).abs() < 2e-3 && range["min"]["value"] == 0.0, "{v}");
let status = s.execute("results.contour", &json!({"step": "Squeeze", "field": "contact_status"})).unwrap();
assert_eq!(status["contour"]["range"]["max"]["value"], 1.0, "{status}");
// The linear analyses refuse the contact by name.
s.execute(
"model.step.create",
&json!({"name": "Linear", "procedure": {"type": "static"}, "boundary_conditions": ["base", "push"], "loads": []}),
)
.unwrap();
let e = s.execute("solve.static", &json!({"step": "Linear"})).unwrap_err().to_string();
assert!(e.contains("interface"), "{e}");
}
#[test]
fn solve_and_probe_a_frictional_contact() {
let mut s = Session::default();
pressed_blocks(&mut s);
s.execute("interaction.contact.edit", &json!({"name": "interface", "surfaces": {"type": "pair", "main": "lower_top", "secondary": "upper_bottom"}, "friction": {"static": 0.2}})).unwrap();
s.execute(
"model.boundary_condition.edit",
&json!({"name": "push", "type": "displacement", "target": {"set": "top"}, "values": [0.05, 0, -0.02, null, null, null]}),
)
.unwrap();
let r = s.execute("solve.nonlinear", &json!({"step": "Squeeze"})).unwrap();
let c = &r["contacts"][0];
assert_eq!(c["slipping_nodes"], 16, "{r}");
// Slipping, the interface carries μ N sideways.
let (n, t) = (c["force"][2].as_f64().unwrap(), c["force"][0].as_f64().unwrap());
assert!((t + 0.2 * n).abs() < 1e-3 * n, "{r}");
let third = 1.0 / 3.0;
let probe = s.execute("solve.probe", &json!({"step": "Squeeze", "at": [[third, third, 1.0]]})).unwrap();
let contact = &probe["nodes"][0]["contact"][0];
assert_eq!(contact["status"], "slip", "{probe}");
assert!(contact["shear"][0].as_f64().unwrap() < 0.0 && contact["slip"][0].as_f64().unwrap() > 0.0, "{probe}");
let v = s.execute("results.contour", &json!({"step": "Squeeze", "field": "contact_status"})).unwrap();
assert_eq!(v["contour"]["range"]["max"]["value"], 2.0, "{v}");
let v = s.execute("results.contour", &json!({"step": "Squeeze", "field": "contact_shear"})).unwrap();
assert!(v["contour"]["range"]["max"]["value"].as_f64().unwrap() > 1.0, "{v}");
}
}
+166
View File
@@ -0,0 +1,166 @@
//! `model.boundary_condition.symmetry`: a symmetry condition on a datum plane, so half of a
//! symmetric part can be solved as a half.
//!
//! The condition holds the displacement normal to the plane, and the rotations about the two
//! axes in it, at zero (`type: "symmetry"`). Its set is given, or made of the faces of the open
//! design's bodies that lie on the plane (the cut faces of a partition by that datum, `partition:
//! <name>:a|b`), so it follows the geometry through a remesh.
use fieldcraft_geometry::FaceSurface;
use fieldcraft_model::{BoundaryCondition, GeometryRef, Set, Symmetry, Target};
use serde_json::{Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const SYMMETRY: CommandSpec = CommandSpec {
id: "model.boundary_condition.symmetry",
label: "Symmetry Plane",
params: r#"{"name": "Sym", "datum": "Mid" (a datum plane normal to X, Y or Z), "set"?: "cut" (default: a new set of the same name holding every face of the open design's bodies on the plane, e.g. a partition's cut faces), "bodies"?: ["Part/a"] (only their faces)} — a symmetry boundary condition on the plane: zero displacement normal to it and zero rotation about the axes in it, so half a symmetric part (loaded symmetrically, with half the load) is solved as a half. Add it to the steps (model.step.activate). Planes not normal to X, Y or Z are not supported yet"#,
form: Some(super::forms::SYMMETRY),
kind: CommandKind::Model,
requires: &[Requirement::DatumPlane],
run: symmetry,
};
/// A face lies on the plane within this fraction of its body's size.
const ON_PLANE: f64 = 1e-6;
fn symmetry(s: &mut Session, p: &Value) -> Result<Value> {
let name = super::name(p)?.to_string();
let datum: String = super::req(p, "datum")?;
let (point, normal) = s
.model
.datum(&datum)
.and_then(|d| d.plane())
.ok_or_else(|| EngineError::Params(format!("no datum plane `{}`", datum.chars().take(64).collect::<String>())))?;
let axis = (0..3).find(|&k| (normal[k].abs() - 1.0).abs() < 1e-9).ok_or_else(|| {
EngineError::Params(format!("not supported yet: symmetry about a plane not normal to X, Y or Z (datum `{datum}` has normal {normal:?})"))
})?;
let plane = [Symmetry::X, Symmetry::Y, Symmetry::Z][axis];
let set = match p.get("set") {
Some(_) => super::req::<String>(p, "set")?,
None => {
let only: Option<Vec<String>> = super::opt(p, "bodies")?;
let design =
s.design.as_deref().ok_or_else(|| EngineError::Params("open a design to find the faces on the plane, or give `set`".into()))?;
let mut faces = Vec::new();
for b in &design.bodies {
if only.as_ref().is_some_and(|o| !o.contains(&b.name)) {
continue;
}
let tol = ON_PLANE * b.size()?.max(1.0);
for (f, surface) in b.faces().iter().zip(b.face_surfaces()?) {
if let Some(FaceSurface::Plane { normal: m, point: q }) = surface {
let parallel = (m[axis].abs() - 1.0).abs() < 1e-9;
if parallel && (q[axis] - point[axis]).abs() < tol {
faces.push(GeometryRef::face(b.name.as_str(), f.name.as_str())?);
}
}
}
}
if faces.is_empty() {
return Err(EngineError::Params(format!("no face of the design lies on datum `{datum}`: partition by it first, or give `set`")));
}
s.model.add_set(&name, Set::of_geometry(faces))?;
name.clone()
}
};
s.model.add_boundary_condition(&name, BoundaryCondition::Symmetry { target: Target::Set(set.clone()), plane })?;
let faces = s.model.set(&set).map_or(0, |x| x.geometry.len());
let axis_name = ["x", "y", "z"].get(axis).copied().unwrap_or("x");
Ok(json!({"name": name, "set": set, "plane": axis_name, "faces": faces}))
}
#[cfg(test)]
mod tests {
use super::*;
/// A 40 × 10 × 10 bar along x (0..40, 0..10, 0..10), the datum `Mid` at y = 5.
fn bar(half: bool) -> (crate::tests::TempDir, Session) {
let commands = json!({"commands": [
{"command": "solid.box", "params": {"length": 40, "width": 10, "height": 10, "body_name": "Bar"}},
]});
let bytes = fieldcraft_geometry::script_design(&commands.to_string()).unwrap();
let (dir, path) = crate::tests::design_file(&bytes);
let mut s = Session::default();
s.execute("geometry.open", &json!({"path": path})).unwrap();
s.execute("geometry.datum", &json!({"name": "Mid", "by": {"type": "offset", "plane": "zx", "offset": 5}})).unwrap();
if half {
s.execute("geometry.partition", &json!({"name": "Half", "datum": "Mid"})).unwrap();
}
(dir, s)
}
fn face(s: &Session, body: &str, point: [f64; 3]) -> String {
let shape = s.design.as_ref().unwrap().body(body).unwrap();
let f = shape.nearest_faces(&[point], 0.01).unwrap()[0].unwrap();
shape.faces()[f as usize].name.clone()
}
/// Clamp the x = 0 end and push the x = 40 end down (−z) with `force`, solve, and give the
/// largest downward tip deflection and the clamp's reaction.
fn bend(s: &mut Session, body: &str, force: f64, extra: &[&str]) -> (f64, f64) {
let (root, tip) = (face(s, body, [0.0, 2.5, 5.0]), face(s, body, [40.0, 2.5, 5.0]));
let mut bcs = vec!["Clamp".to_string()];
bcs.extend(extra.iter().map(|x| x.to_string()));
let script = json!([
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": body}]}},
{"command": "model.set.create", "params": {"name": "root", "geometry": [{"body": body, "face": root}]}},
{"command": "model.set.create", "params": {"name": "tip", "geometry": [{"body": body, "face": tip}]}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
{"command": "model.section.create", "params": {"name": "Bar", "set": "all", "material": "Steel", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "root"}}},
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"set": "tip"}, "vector": [0, 0, -force]}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": bcs, "loads": ["Push"]}},
]);
s.run_script(&script).unwrap();
s.execute("solve.static", &json!({})).unwrap();
let tip = s.model.resolve_set("tip").unwrap().nodes;
let probe = s.execute("solve.probe", &json!({"step": "Load", "nodes": tip})).unwrap();
let w = probe["nodes"].as_array().unwrap().iter().map(|n| -n["displacement"][2].as_f64().unwrap()).fold(f64::MIN, f64::max);
let r = s.execute("results.reactions", &json!({"step": "Load", "sets": ["root"]})).unwrap();
(w, r["sets"][0]["force"][2].as_f64().unwrap_or(f64::NAN))
}
/// Half the bar, cut on its symmetry plane y = 5, with the symmetry condition and half the
/// load, bends as the whole bar does: the same deflection, half the reaction.
#[test]
fn a_half_model_with_symmetry_matches_the_whole() {
let (_d1, mut whole) = bar(false);
whole.execute("mesh.hex.mapped", &json!({"body": "Bar", "size": 2.5, "order": 2})).unwrap();
let full = bend(&mut whole, "Bar", 1000.0, &[]);
let (_d2, mut half) = bar(true);
half.execute("mesh.hex.mapped", &json!({"body": "Bar/a", "size": 2.5, "order": 2})).unwrap();
let r = half.execute("model.boundary_condition.symmetry", &json!({"name": "Sym", "datum": "Mid", "bodies": ["Bar/a"]})).unwrap();
assert_eq!(r, json!({"name": "Sym", "set": "Sym", "plane": "y", "faces": 1}));
assert_eq!(half.model.set("Sym").unwrap().geometry[0].entity, fieldcraft_model::geometry::Entity::Face("partition:Half:a".into()));
let halved = bend(&mut half, "Bar/a", 500.0, &["Sym"]);
assert!((halved.0 - full.0).abs() < 1e-9 * full.0, "deflection {} vs {}", halved.0, full.0);
assert!((2.0 * halved.1 - full.1).abs() < 1e-9 * full.1.abs(), "reaction {} vs {}", halved.1, full.1);
}
#[test]
fn inclined_planes_and_hostile_params_change_nothing() {
let (_d, mut s) = bar(true);
s.execute("geometry.datum", &json!({"name": "Tilt", "by": {"type": "point_normal", "point": [0, 0, 0], "normal": [1, 1, 0]}})).unwrap();
s.execute("geometry.datum", &json!({"name": "Out", "by": {"type": "offset", "plane": "xy", "offset": 100}})).unwrap();
s.execute("geometry.datum.axis", &json!({"name": "Ax", "by": {"type": "principal", "axis": "x"}})).unwrap();
let model = s.model.clone();
let e = s.execute("model.boundary_condition.symmetry", &json!({"name": "S", "datum": "Tilt"})).unwrap_err();
assert!(e.to_string().contains("not supported yet"), "{e}");
for p in [
json!({"name": "S", "datum": "Out"}),
json!({"name": "S", "datum": "Ax"}),
json!({"name": "S", "datum": "Nope"}),
json!({"name": "S", "datum": "Mid", "set": "nope"}),
json!({"name": "S", "datum": "Mid", "bodies": ["Nope"]}),
json!({"name": "1S", "datum": "Mid"}),
json!({"datum": "Mid"}),
] {
assert!(s.execute("model.boundary_condition.symmetry", &p).is_err(), "{p}");
}
assert_eq!(s.model, model);
}
}
+13 -3
View File
@@ -1,10 +1,12 @@
//! Geometry tags on the mesh: which body, face, edge or vertex each mesh entity lies on. Meshers
//! write them; these commands set them by hand (for a mesh from elsewhere) and clear them.
use crate::schema::ProblemKind;
use fieldcraft_model::{ElementFace, GeometryRef, MAX_ELEMENTS};
use serde_json::{Value, json};
use super::{opt, req};
use crate::requirement::Requirement;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const TAG: CommandSpec = CommandSpec {
@@ -13,11 +15,19 @@ pub const TAG: CommandSpec = CommandSpec {
params: r#"{"geometry": {"body": "Body1"} | {"body", "face"} | {"body", "edge"} | {"body", "vertex"}, "elements": [labels] (filling a body, face or edge), "faces": [{"element": 1, "face": 3}] (on a face), "edges": [{"element": 1, "edge": 2}] (on an edge), "nodes": [labels] (on a vertex)} — records where the mesh lies on the geometry, so sets named by geometry resolve"#,
form: Some(super::forms::TAG),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: tag,
};
pub const TAG_CLEAR: CommandSpec =
CommandSpec { id: "mesh.tag.clear", label: "Clear Geometry Tags", params: "{}", form: Some(&[]), kind: CommandKind::Model, run: tag_clear };
pub const TAG_CLEAR: CommandSpec = CommandSpec {
id: "mesh.tag.clear",
label: "Clear Geometry Tags",
params: "{}",
form: Some(&[]),
kind: CommandKind::Model,
requires: &[Requirement::Mesh],
run: tag_clear,
};
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
@@ -29,7 +39,7 @@ struct ElementEdge {
/// An optional list parameter of at most [`MAX_ELEMENTS`] entries.
fn list<'a, T: serde::Deserialize<'a>>(p: &'a Value, key: &str) -> Result<Vec<T>> {
if p.get(key).and_then(Value::as_array).is_some_and(|a| a.len() > MAX_ELEMENTS) {
return Err(EngineError::Params(format!("`{key}` must be a list of at most {MAX_ELEMENTS} entries")));
return Err(EngineError::param(key, ProblemKind::NotAList { max: MAX_ELEMENTS, what: "entries" }));
}
Ok(opt(p, key)?.unwrap_or_default())
}
+59
View File
@@ -0,0 +1,59 @@
//! `app.update.check`: is a newer FieldCraft published? The same check as the desktop app's
//! Help › Check for Updates and `fieldcraft-cli update --check` (docs/updates.md). It only
//! reports: nothing is downloaded or installed, and no dialog opens.
//!
//! Checking reaches the network, so it is switched on only by the programs that may
//! ([`enable_checks`]: the desktop app and the CLI); everywhere else (tests, scratch sessions,
//! the browser) the command refuses without asking anything.
use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::Value;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const CHECK: CommandSpec = CommandSpec {
id: "app.update.check",
label: "Check for Updates",
params: r#"{} — asks GitHub Releases for the latest published FieldCraft release and compares it with this version: current, latest, newer, url (its page and release notes), published, signed (whether it can be verified and installed from the app) and asset (the file this install would download; null when it cannot update itself). Reports only: nothing is downloaded or installed. Desktop app and fieldcraft-cli only"#,
form: Some(&[]),
kind: CommandKind::Session,
requires: &[],
run: check,
};
static ENABLED: AtomicBool = AtomicBool::new(false);
/// Let `app.update.check` reach the release server (the desktop app and the CLI do).
pub fn enable_checks(on: bool) {
ENABLED.store(on, Ordering::SeqCst);
}
#[cfg(target_arch = "wasm32")]
fn check(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Params("not in the browser: the web app offers Reload to update when a new version is deployed".into()))
}
#[cfg(not(target_arch = "wasm32"))]
fn check(_: &mut Session, _: &Value) -> Result<Value> {
if !ENABLED.load(Ordering::SeqCst) {
return Err(EngineError::Params("update checks are off in this session (the desktop app and fieldcraft-cli check for updates)".into()));
}
let check = fieldcraft_update::net::Client::from_env().check().map_err(|e| EngineError::Params(e.to_string()))?;
let asset = fieldcraft_update::install::here().asset_name(&check.latest.version, std::env::consts::ARCH);
Ok(check.to_json(asset.as_deref()))
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
/// Off unless a program switches it on: tests and scratch sessions never reach the network.
#[test]
fn checks_are_off_unless_enabled() {
let e = Session::default().execute("app.update.check", &json!({})).unwrap_err();
assert!(e.to_string().contains("update checks are off"), "{e}");
}
}
+219
View File
@@ -0,0 +1,219 @@
//! What the viewport hides: `view.hide`, `view.show`, `view.isolate` and `view.show_all`.
//!
//! The hidden items (bodies, imported surfaces, datums, boundary conditions, loads, reference
//! points, couplings) are view state ([`fieldcraft_io::View`]): saved with the model and marking
//! it unsaved, but not a definition, so they are neither journalled nor undone and they leave
//! results current. A hidden item is not drawn, so it cannot be picked either. An item that goes
//! away (deleted, or a body cut into cells) is forgotten.
use std::collections::BTreeSet;
use fieldcraft_io::{Item, ItemKind, MAX_HIDDEN};
use serde_json::Value;
use crate::{CommandKind, CommandSpec, EngineError, Result, Session};
pub const HIDE: CommandSpec = CommandSpec {
id: "view.hide",
label: "Hide",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — hides the items in the viewport (and from picking); view state, saved with the model"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Hide),
};
pub const SHOW: CommandSpec = CommandSpec {
id: "view.show",
label: "Show",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — shows hidden items again"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Show),
};
pub const ISOLATE: CommandSpec = CommandSpec {
id: "view.isolate",
label: "Isolate",
params: concat!(
r#"{"items": [{"kind": "body" | "surface" | "datum" | "boundary_condition" | "load" | "reference_point" | "coupling", "name": "Sym"}]}"#,
" — shows only these items: every other one is hidden (view.show_all brings them back)"
),
form: Some(super::forms::VIEW_ITEMS),
kind: CommandKind::Session,
requires: &[],
run: |s, p| change(s, p, Change::Isolate),
};
pub const SHOW_ALL: CommandSpec = CommandSpec {
id: "view.show_all",
label: "Show All",
params: "{}",
form: Some(&[]),
kind: CommandKind::Session,
requires: &[],
run: |s, _| {
s.view.hidden.clear();
Ok(Value::Null)
},
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Change {
Hide,
Show,
Isolate,
}
/// Every item of `kind` the session has, by name.
pub(crate) fn names(s: &Session, kind: ItemKind) -> Vec<String> {
let m = &s.model;
match kind {
ItemKind::Body => s.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.clone())).collect(),
ItemKind::Surface => s.surfaces.iter().map(|x| x.name.clone()).collect(),
ItemKind::Datum => m.datums().keys().cloned().collect(),
ItemKind::BoundaryCondition => m.boundary_conditions().keys().cloned().collect(),
ItemKind::Load => m.loads().keys().cloned().collect(),
ItemKind::ReferencePoint => m.reference_points().keys().cloned().collect(),
ItemKind::Coupling => m.couplings().keys().cloned().collect(),
}
}
fn exists(s: &Session, item: &Item) -> bool {
let m = &s.model;
match item.kind {
ItemKind::Body => s.design.as_ref().is_some_and(|d| d.body(&item.name).is_some()),
ItemKind::Surface => s.surfaces.iter().any(|x| x.name == item.name),
ItemKind::Datum => m.datum(&item.name).is_some(),
ItemKind::BoundaryCondition => m.boundary_conditions().contains_key(&item.name),
ItemKind::Load => m.loads().contains_key(&item.name),
ItemKind::ReferencePoint => m.reference_points().contains_key(&item.name),
ItemKind::Coupling => m.couplings().contains_key(&item.name),
}
}
/// Forget hidden items the session no longer has.
pub(crate) fn forget_missing(s: &mut Session) {
if s.view.hidden.is_empty() {
return;
}
let gone: Vec<Item> = s.view.hidden.iter().filter(|i| !exists(s, i)).cloned().collect();
for i in gone {
s.view.hidden.remove(&i);
}
}
impl Session {
/// The analysis setup's symbols, without the definitions the view hides.
pub fn glyphs(&self) -> fieldcraft_render::glyphs::Glyphs {
use fieldcraft_render::glyphs::Definition;
fieldcraft_render::glyphs::Glyphs::from_model_hiding(&self.model, &|definition, name| {
let kind = match definition {
Definition::BoundaryCondition => ItemKind::BoundaryCondition,
Definition::Load => ItemKind::Load,
Definition::ReferencePoint => ItemKind::ReferencePoint,
Definition::Coupling => ItemKind::Coupling,
Definition::Contact | Definition::Tie | Definition::Step => return false,
};
self.view.is_hidden(kind, name)
})
}
/// Whether the view shows item `name` of `kind`.
pub fn shows(&self, kind: ItemKind, name: &str) -> bool {
!self.view.is_hidden(kind, name)
}
}
fn change(s: &mut Session, p: &Value, how: Change) -> Result<Value> {
let items: Vec<Item> = super::req(p, "items")?;
if items.len() > MAX_HIDDEN {
return Err(EngineError::Params(format!("at most {MAX_HIDDEN} items")));
}
if let Some(i) = items.iter().find(|i| !exists(s, i)) {
let kind = serde_json::to_value(i.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
return Err(EngineError::Params(format!("no {} `{}`", kind.replace('_', " "), i.name.chars().take(100).collect::<String>())));
}
match how {
Change::Hide => s.view.hidden.extend(items),
Change::Show => {
for i in &items {
s.view.hidden.remove(i);
}
}
Change::Isolate => {
let keep: BTreeSet<Item> = items.into_iter().collect();
let all = ItemKind::ALL.into_iter().flat_map(|kind| names(s, kind).into_iter().map(move |name| Item { kind, name }));
let rest: BTreeSet<Item> = all.filter(|i| !keep.contains(i)).take(MAX_HIDDEN).collect();
s.view.hidden = rest;
}
}
Ok(Value::Null)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::cmd::datum::tests::plate;
fn item(kind: ItemKind, name: &str) -> Value {
json!({"kind": kind, "name": name})
}
#[test]
fn hiding_is_saved_view_state_not_an_edit() {
let (mut s, dir) = plate();
s.execute("geometry.datum", &json!({"name": "Sym", "by": {"type": "offset", "plane": "zx"}})).unwrap();
s.execute("geometry.datum.point", &json!({"name": "P", "by": {"type": "coordinates", "point": [1, 2, 3]}})).unwrap();
let file = dir.join("hide.fieldcraft");
s.execute("file.save_as", &json!({"path": file.to_str().unwrap()})).unwrap();
let (journal, revision) = (s.journal.len(), s.revision());
assert!(!s.is_dirty());
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
assert_eq!(s.view.hidden.iter().collect::<Vec<_>>(), [&Item { kind: ItemKind::Datum, name: "Sym".into() }]);
// Unsaved, but no edit: nothing journalled, the revision (and so any result) unchanged.
assert!(s.is_dirty());
assert_eq!((s.journal.len(), s.revision()), (journal, revision));
// Showing it again is back to the saved state.
s.execute("view.show", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
assert!(!s.is_dirty());
// Hidden state survives save and open.
s.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "Sym")]})).unwrap();
s.execute("file.save", &json!({})).unwrap();
let mut t = Session::default();
t.execute("file.open", &json!({"path": file.to_str().unwrap()})).unwrap();
assert!(t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
assert!(!t.is_dirty());
// Isolate hides every other item; show_all brings them back.
let body = names(&t, ItemKind::Body).remove(0);
t.execute("view.isolate", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
assert!(t.view.is_hidden(ItemKind::Body, &body) && t.view.is_hidden(ItemKind::Datum, "Sym") && !t.view.is_hidden(ItemKind::Datum, "P"));
t.execute("view.show_all", &json!({})).unwrap();
assert!(t.view.is_empty());
// An item deleted is forgotten.
t.execute("view.hide", &json!({"items": [item(ItemKind::Datum, "P")]})).unwrap();
t.execute("geometry.datum.delete", &json!({"name": "P"})).unwrap();
assert!(t.view.is_empty());
// Unknown items and hostile parameters change nothing.
for p in [json!({}), json!({"items": "x"}), json!({"items": [item(ItemKind::Load, "Nope")]}), json!({"items": [{"kind": "x", "name": "A"}]})]
{
assert!(t.execute("view.hide", &p).is_err(), "{p}");
}
assert!(t.view.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
use super::*;
use crate::Session;
fn fresh_dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("fieldcraft-crash-test-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
d
}
fn build() -> Build {
Build { version: "9.9.9", commit: "abc1234" }
}
fn node(label: u32) -> Value {
json!({"label": label, "xyz": [f64::from(label), 0.0, 0.0]})
}
/// The child half of the process tests: does nothing unless a parent asks, then installs the
/// hook and crashes the way `FIELDCRAFT_CRASH_CHILD` says.
#[test]
fn child() {
let (Some(dir), Ok(mode)) = (std::env::var_os("FIELDCRAFT_CRASH_CHILD_DIR"), std::env::var("FIELDCRAFT_CRASH_CHILD")) else {
return;
};
let dir = PathBuf::from(dir);
if mode == "replay" {
// Replay the one report (in a process of its own: the replay replaces the panic hook).
let id = list(&dir)[0].id.clone();
let r = replay(&read(&dir, &id).unwrap(), &std::env::temp_dir()).unwrap();
let steps: Vec<_> = r.steps.iter().map(|(c, r)| json!({"command": c, "ok": r.is_ok()})).collect();
println!("REPLAY {}", json!({"reproduced": r.reproduced, "nodes": r.session.model.nodes().len(), "steps": steps}));
return;
}
let fresh = install(dir.clone(), build());
println!("FRESH {}", serde_json::to_string(&fresh).unwrap());
if mode == "idle" {
end_session();
return;
}
let mut s = Session { crash_journal: true, ..Default::default() };
s.execute("mesh.node.add", &node(1)).unwrap();
s.execute("mesh.node.add", &node(2)).unwrap();
// Commands that only read are not kept.
for _ in 0..50 {
s.execute("model.info", &json!({})).unwrap();
}
match mode.as_str() {
"command" => {
for _ in 0..3 {
let r = s.execute("diagnostics.crash_test", &json!({"mode": "panic"}));
assert!(matches!(r, Err(crate::EngineError::Internal { .. })), "{r:?}");
}
assert_eq!(s.model.nodes().len(), 2, "the model is unchanged");
}
"recovered" => {
assert_eq!(s.execute("diagnostics.crash_test", &json!({"mode": "recovered"})).unwrap()["caught"], true);
}
"thread" => {
let r = std::thread::Builder::new()
.name("worker".into())
.spawn(|| std::panic::panic_any(String::from("worker thread 42 failed")))
.unwrap()
.join();
assert!(r.is_err());
}
"abort" => {
activity("control ui.capture");
let _ = s.execute("diagnostics.crash_test", &json!({"mode": "abort"}));
}
"autosave" => {
// The journal starts again from each autosave.
let mut a = crate::autosave::Autosaver::new(&dir.join("recovery")).unwrap();
assert!(a.save(&s).unwrap());
s.execute("mesh.node.add", &node(3)).unwrap();
activity("control ui.capture");
std::process::abort();
}
_ => {}
}
end_session();
}
/// Run [`child`] in a new process; returns its stdout and whether it succeeded.
fn run_child(dir: &Path, mode: &str) -> (String, bool) {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "crash::tests::child", "--test-threads=1", "--nocapture"])
.env("FIELDCRAFT_CRASH_CHILD_DIR", dir)
.env("FIELDCRAFT_CRASH_CHILD", mode)
.env("FIELDCRAFT_CRASH_TEST", "1")
.env("RUST_BACKTRACE", "0")
.output()
.unwrap();
(String::from_utf8_lossy(&out.stdout).into_owned(), out.status.success())
}
fn printed(out: &str, tag: &str) -> Value {
let line = out.lines().find_map(|l| l.split_once(tag).map(|(_, rest)| rest)).unwrap_or_else(|| panic!("no {tag} in {out}"));
serde_json::from_str(line.trim()).unwrap()
}
fn only_report(dir: &Path) -> (Summary, Value) {
let all = list(dir);
assert_eq!(all.len(), 1, "{all:?}");
let s = all.into_iter().next().unwrap();
let v = read(dir, &s.id).unwrap();
(s, v)
}
fn nodes_in(model: &str) -> usize {
let mut s = Session::default();
s.execute("file.open", &json!({"path": model})).unwrap();
s.model.nodes().len()
}
#[test]
fn a_command_panic_is_reported_once_with_the_model_and_the_command_and_replays() {
let d = fresh_dir("command");
let (_, ok) = run_child(&d, "command");
assert!(ok, "the panics were caught");
let (s, v) = only_report(&d);
assert_eq!(s.kind, "command_panic");
assert_eq!(s.count, 3, "repeats are counted, not written again");
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"));
assert!(s.replayable);
assert_eq!(v["format"], FORMAT);
assert_eq!(v["app"]["version"], "9.9.9");
assert_eq!(v["system"]["os"], std::env::consts::OS);
assert!(v["message"].as_str().unwrap().contains("an internal error in a command"), "{v}");
assert!(v["location"].as_str().unwrap().contains("diagnostics.rs"), "{v}");
let bt = v["backtrace"].as_array().unwrap();
assert!(bt.iter().any(|f| f.as_str().unwrap().contains("crash_test")), "{bt:?}");
assert!(!bt.iter().any(|f| f.as_str().unwrap().contains("crash::hook")), "the hook's own frames are dropped: {bt:?}");
assert_eq!(v["recent_commands"][0]["command"], "mesh.node.add");
assert_eq!(v["recent_commands"].as_array().unwrap().len(), 3, "read-only commands are not kept: {v}");
assert_eq!(v["recent_commands"][2]["ok"], false);
// The model from before the command, and the command: together they reproduce the crash.
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2);
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"], json!([{"command": "diagnostics.crash_test", "params": {"mode": "panic"}}]));
assert_eq!(v["reproduce"], format!("fieldcraft-cli crashes replay {}", s.id));
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "a clean exit leaves no journal");
// The replay reaches the same internal error, from the same model.
let (out, ok) = run_child(&d, "replay");
assert!(ok, "{out}");
let r = printed(&out, "REPLAY ");
assert_eq!(r["reproduced"], true, "{r}");
assert_eq!(r["nodes"], 2, "the replay ends in the state the crash left: {r}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_panic_caught_inside_a_command_is_reported_as_recovered() {
let d = fresh_dir("recovered");
let (_, ok) = run_child(&d, "recovered");
assert!(ok);
let (s, v) = only_report(&d);
assert_eq!(s.kind, "recovered_panic");
assert!(!s.replayable, "the command did not fail");
assert!(v["message"].as_str().unwrap().contains("caught inside"), "{v}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_panic_outside_commands_is_reported_from_the_journal() {
let d = fresh_dir("thread");
let (_, ok) = run_child(&d, "thread");
assert!(ok);
let (s, v) = only_report(&d);
assert_eq!(s.kind, "panic");
assert_eq!(v["thread"], "worker");
assert!(s.message.contains("worker thread 42 failed"));
// The journal's commands from a new model rebuild it.
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"].as_array().unwrap().len(), 2, "{replay}");
// A panic the hook reported is no unclean exit at the next start.
let (out, _) = run_child(&d, "abort");
let fresh = printed(&out, "FRESH ");
assert_eq!(fresh.as_array().unwrap().len(), 1, "the earlier report, seen once: {fresh}");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn an_unclean_exit_is_found_at_the_next_start_with_its_commands() {
let d = fresh_dir("abort");
let (_, ok) = run_child(&d, "abort");
assert!(!ok, "the child aborted");
assert!(list(&d).is_empty(), "nothing wrote a report while it died");
assert_eq!(fs::read_dir(d.join("sessions")).unwrap().count(), 1, "its journal is left behind");
let (out, ok) = run_child(&d, "idle");
assert!(ok);
let fresh = printed(&out, "FRESH ");
assert_eq!(fresh[0]["kind"], "unclean_exit", "{fresh}");
let (s, v) = only_report(&d);
assert_eq!(s.command.as_deref(), Some("diagnostics.crash_test"), "the command in flight");
assert!(s.message.contains("ended without a clean exit while running `diagnostics.crash_test`"), "{}", s.message);
assert_eq!(v["last_activity"], "control ui.capture");
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
let ids: Vec<&str> = replay["commands"].as_array().unwrap().iter().map(|c| c["command"].as_str().unwrap()).collect();
assert_eq!(ids, ["mesh.node.add", "mesh.node.add", "diagnostics.crash_test"]);
assert!(fs::read_dir(d.join("sessions")).unwrap().next().is_none(), "the dead journal is gone");
// Told once: the next start offers nothing new.
let (out, _) = run_child(&d, "idle");
assert_eq!(printed(&out, "FRESH "), json!([]));
let _ = fs::remove_dir_all(&d);
}
#[test]
fn an_unclean_exit_after_an_autosave_starts_from_the_autosave() {
let d = fresh_dir("autosave");
let (_, ok) = run_child(&d, "autosave");
assert!(!ok);
run_child(&d, "idle");
let (s, v) = only_report(&d);
assert_eq!(s.kind, "unclean_exit");
assert!(s.message.contains("between commands (last: control ui.capture)"), "{}", s.message);
assert_eq!(nodes_in(v["model_path"].as_str().unwrap()), 2, "the autosaved model");
let replay: Value = serde_json::from_slice(&fs::read(v["replay_path"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(replay["commands"], json!([{"command": "mesh.node.add", "params": node(3)}]), "only what came after the autosave");
let (out, ok) = run_child(&d, "replay");
assert!(ok, "{out}");
assert_eq!(printed(&out, "REPLAY ")["nodes"], 3, "the replay rebuilds the model the app had");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn journals_parse_and_hostile_ids_are_refused() {
let text = [
r#"{"start":"x","pid":1,"version":"1"}"#,
r#"{"base":"new"}"#,
r#"{"run":"a","params":{}}"#,
r#"{"ok":true}"#,
r#"{"activity":"control ui.capture"}"#,
r#"{"run":"b","params":{"x":1}}"#,
r#"{"ok":false,"error":"no"}"#,
"not json",
r#"{"run":"c","params":{}}"#,
]
.join("\n");
let j = parse_journal(&text);
assert_eq!(j.replay, vec![json!({"command": "a", "params": {}})]);
assert_eq!(j.recent.len(), 2);
assert_eq!(j.in_flight, Some(json!({"command": "c", "params": {}})));
assert_eq!(j.activity.as_deref(), Some("control ui.capture"));
assert!(j.complete && !j.reported);
let d = fresh_dir("hostile");
fs::create_dir_all(&d).unwrap();
for id in ["", "../x", "a/b", &"f".repeat(65)] {
assert!(read(&d, id).is_err(), "{id}");
assert_eq!(clear(&d, Some(id)), 0);
}
let _ = fs::remove_dir_all(&d);
}
#[test]
fn signatures_ignore_numbers() {
assert_eq!(signature("a.rs:1", "node 12 of 400"), signature("a.rs:1", "node 7 of 3"));
assert_ne!(signature("a.rs:1", "node 12"), signature("a.rs:2", "node 12"));
assert_eq!(utc(0), "1970-01-01T00:00:00Z");
assert_eq!(stamp(1_760_436_000), "20251014-100000");
}
#[test]
fn reports_are_pruned_to_the_limits() {
let d = fresh_dir("prune");
for i in 0..(MAX_REPORTS + 5) {
let id = format!("20261014-1000{:02}-{:016x}", i % 60, i + 1);
fs::create_dir_all(d.join(&id)).unwrap();
let kind = if i == MAX_REPORTS + 4 { "recovered_panic" } else { "panic" };
fs::write(d.join(&id).join("report.json"), json!({"kind": kind, "message": "m"}).to_string()).unwrap();
}
prune(&d, now());
let left = list(&d);
assert_eq!(left.len(), MAX_REPORTS);
assert!(left.iter().all(|r| r.kind == "panic"), "recovered ones go first");
assert_eq!(clear(&d, None), MAX_REPORTS);
let _ = fs::remove_dir_all(&d);
}
+29
View File
@@ -6,6 +6,11 @@
//! journal always replays to the current model, and the undo steps are the journal's last
//! entries, newest last. A new command clears the redo stack.
//!
//! A step also carries the session's [`Document`] (its file and the revision saved there) when
//! its command changed which document the session is, as `geometry.open` with `"model": "new"`
//! does: undo makes the previous file current again, redo the new untitled model. Other steps
//! leave the document alone, so saving between edits and then undoing them keeps the file.
//!
//! History is bounded by step count ([`MAX_UNDO_STEPS`]) and by an estimate of the memory the
//! kept states hold ([`DEFAULT_UNDO_MEMORY`], [`Session::set_undo_memory`]): when either is
//! exceeded, the oldest undo steps go first, then the redo steps farthest from the current state.
@@ -46,6 +51,16 @@ pub(crate) struct State {
surfaces: Vec<Arc<TaggedSurface>>,
sources: fieldcraft_io::Geometry,
revision: u64,
/// The document before the step, when the step changed it.
pub(crate) document: Option<Document>,
}
/// Which document the session is: the `.fieldcraft` file it belongs to and the revision saved
/// there ([`Session::is_dirty`]).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Document {
pub(crate) path: Option<String>,
pub(crate) saved_revision: Option<u64>,
}
#[derive(Debug, Clone)]
@@ -147,6 +162,19 @@ impl Session {
surfaces: self.surfaces.clone(),
sources: self.sources.clone(),
revision: self.revision,
document: None,
}
}
pub(crate) fn document(&self) -> Document {
Document { path: self.path.clone(), saved_revision: self.saved_revision }
}
/// Make `document` current; returns the one it replaces.
pub(crate) fn set_document(&mut self, document: Document) -> Document {
Document {
path: std::mem::replace(&mut self.path, document.path),
saved_revision: std::mem::replace(&mut self.saved_revision, document.saved_revision),
}
}
@@ -158,6 +186,7 @@ impl Session {
surfaces: std::mem::replace(&mut self.surfaces, state.surfaces),
sources: std::mem::replace(&mut self.sources, state.sources),
revision: std::mem::replace(&mut self.revision, state.revision),
document: state.document.map(|d| self.set_document(d)),
}
}
+245 -6
View File
@@ -13,14 +13,23 @@
#![forbid(unsafe_code)]
pub mod autosave;
pub mod bug_report;
pub mod catalogue;
pub mod cmd;
pub mod crash;
pub mod logfile;
pub use cmd::analytic_surfaces;
pub use cmd::replace::{MESHERS, Replacement, replacement};
pub use cmd::update::enable_checks as enable_update_checks;
pub use fieldcraft_io::{Item as ViewItem, ItemKind};
pub mod history;
pub mod progress;
pub mod requirement;
pub mod results;
pub mod sample;
pub mod schema;
pub mod usage;
pub mod view;
use std::collections::BTreeMap;
@@ -40,6 +49,11 @@ pub enum EngineError {
UnknownCommand(String),
#[error("{0}")]
Params(String),
/// One parameter is missing or wrong: the schema's [`schema::Problem`], at the field's JSON
/// path (`elastic/young`). The message names the key ([`schema::Problem::for_agents`]); a
/// form shows it beside the field, by its label ([`schema::Problem::for_form`]).
#[error("{}", .0.for_agents())]
Param(schema::Problem),
#[error(transparent)]
Model(#[from] fieldcraft_model::Error),
#[error(transparent)]
@@ -56,11 +70,27 @@ pub enum EngineError {
Explicit(#[from] fieldcraft_explicit::Error),
#[error(transparent)]
Fluid(#[from] fieldcraft_lbm::Error),
/// The session lacks what the command needs ([`requirement`]); nothing was done.
#[error("{0}")]
Unavailable(requirement::Unavailable),
/// A command panicked; the model is unchanged.
#[error("internal error in {command}: {message}")]
Internal { command: String, message: String },
}
impl EngineError {
/// A problem with the parameter at `path` (`elastic/young`).
pub fn param(path: impl Into<String>, kind: schema::ProblemKind) -> Self {
Self::Param(schema::Problem::at(path, kind))
}
/// A parameter problem with something wrong that the schema does not describe: what the
/// value must be or do instead.
pub fn invalid(path: impl Into<String>, why: impl Into<String>) -> Self {
Self::param(path, schema::ProblemKind::Invalid(why.into()))
}
}
pub type Result<T> = std::result::Result<T, EngineError>;
/// The result of a solved step, from the implicit, the explicit or the lattice Boltzmann solver.
@@ -113,6 +143,9 @@ pub struct CommandSpec {
/// (the form is then the JSON text alone).
pub form: Option<&'static [schema::Field]>,
pub kind: CommandKind,
/// What the session must hold before the command can run ([`requirement`]): checked by
/// [`Session::execute`], and by the UI to grey the command with the missing pieces named.
pub requires: &'static [requirement::Requirement],
pub run: fn(&mut Session, &Value) -> Result<Value>,
}
@@ -124,9 +157,9 @@ pub fn commands() -> &'static [CommandSpec] {
impl CommandSpec {
/// The command as JSON for listings (`fieldcraft-cli commands --json`, the control channel's
/// `engine.commands`, MCP `list_commands`): id, label, the parameter doc and, when described,
/// the parameters as JSON Schema.
/// the parameters as JSON Schema, and what it requires.
pub fn listing(&self) -> Value {
let mut v = serde_json::json!({"id": self.id, "label": self.label, "params": self.params});
let mut v = serde_json::json!({"id": self.id, "label": self.label, "params": self.params, "requires": self.requires});
if let Some(form) = self.form {
v["schema"] = schema::json_schema(form);
}
@@ -208,6 +241,21 @@ pub struct Session {
/// The folders commands may read and write files in (an automation client's roots,
/// docs/mcp.md); unconfined by default. A file replacing the session keeps them.
pub file_access: fieldcraft_io::roots::Roots,
/// Identifies the open document: it changes when another model, sample or design is opened
/// in place of the current one, never with an edit (see [`Session::opened`]).
opened: u64,
/// What the viewport hides (`view.*`): saved with the model, but no edit of it, so it is
/// neither journalled nor undone, and it leaves results current.
pub view: fieldcraft_io::View,
/// The view as last saved (or opened): a change to it is unsaved too.
saved_view: fieldcraft_io::View,
/// This is the app's own model: its top-level commands go into the crash journal
/// ([`crash`]), so an unclean exit can be replayed. Off for scratch sessions and tests.
pub crash_journal: bool,
/// Where this session's commands come from, for the usage analytics ([`usage`]): the app
/// sets it on its own model (and the control channel and the command search while they
/// run); `None` (scratch sessions, the CLI, tests) counts nothing.
pub origin: Option<usage::Origin>,
}
impl Session {
@@ -216,11 +264,33 @@ impl Session {
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
// An id from hostile input is not echoed in full.
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.chars().take(100).collect()))?;
let timer = usage::Timer::start(self.origin);
let elements = self.model.elements().len();
let result = self.availability(spec).map_err(EngineError::Unavailable).and_then(|()| self.run_command(spec, params));
if timer.counting() {
let milestone = usage::milestone(spec.id, (elements, self.model.elements().len()));
let sample =
(spec.id == "file.sample").then(|| params.get("name").and_then(Value::as_str).and_then(sample::find)).flatten().map(|s| s.name);
timer.done(spec.id, spec.kind, result.as_ref().err(), milestone, sample);
}
result
}
/// [`Session::execute`] once the command is found and can run.
fn run_command(&mut self, spec: &'static CommandSpec, params: &Value) -> Result<Value> {
let id = spec.id;
// Session commands (open, save, undo, redo) change the session only in their last step,
// after everything that can fail, so they need no copy of the model to restore.
let before = (spec.kind == CommandKind::Model).then(|| self.snapshot());
let before = (spec.kind == CommandKind::Model).then(|| (self.snapshot(), self.document()));
let scope = crash::Scope::enter();
let journaled = crash::command_begin(&scope, self, id, params);
let (revision, opened) = (self.revision, self.opened);
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (spec.run)(self, params)));
let result = match outcome {
Ok(Err(EngineError::Param(p))) => Err(EngineError::Param(match spec.form {
Some(form) => schema::refine(form, params, p),
None => p,
})),
Ok(r) => r,
Err(p) => {
let message = p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_default();
@@ -228,15 +298,24 @@ impl Session {
Err(EngineError::Internal { command: id.to_string(), message })
}
};
if let Some(before) = before {
if let Some((mut before, document)) = before {
// A command that makes the session another document (a new model) keeps the old
// one in its undo step.
if self.document() != document {
before.document = Some(document);
}
if result.is_err() {
self.restore(before);
} else if self.differs_from(&before) {
} else if before.document.is_some() || self.differs_from(&before) {
self.journal.push((id.to_string(), params.clone()));
self.revision = next_revision();
self.record_undo(before);
// An item deleted (or a body cut into cells) is no longer hidden.
cmd::view::forget_missing(self);
}
}
drop(scope);
crash::command_done(self, journaled, self.revision != revision || self.opened != opened, id, params, &result);
result
}
@@ -254,6 +333,19 @@ impl Session {
Ok(outputs)
}
/// Identifies the open document: it changes when `file.open`, `file.recover` or `file.sample`
/// replaces the session and when `geometry.open` opens another design file or starts a new
/// model with one; an edit, a solve, undo, redo or opening the same design again after an
/// edit keep it. A view frames the model again when it changes.
pub fn opened(&self) -> u64 {
self.opened
}
/// Make the session another document (see [`Session::opened`]).
pub(crate) fn mark_opened(&mut self) {
self.opened = next_revision();
}
/// Identifies the current state (see [`Session::is_dirty`]).
pub fn revision(&self) -> u64 {
self.revision
@@ -262,7 +354,7 @@ impl Session {
/// Whether the session has changes its file does not hold. Undoing back to the saved state
/// makes it clean again.
pub fn is_dirty(&self) -> bool {
self.saved_revision.unwrap_or(0) != self.revision
self.saved_revision.unwrap_or(0) != self.revision || self.view != self.saved_view
}
/// The stored result of a step, if it was solved in the current state (an edit makes it stale;
@@ -303,6 +395,7 @@ impl Session {
pub(crate) fn mark_saved(&mut self, path: String) {
self.path = Some(path);
self.saved_revision = Some(self.revision);
self.saved_view = self.view.clone();
}
}
@@ -632,6 +725,10 @@ mod tests {
assert!((volume - expect).abs() < 1e-3 * expect, "{volume}");
let faces = bodies[0]["faces"].as_array().unwrap();
assert_eq!(faces.len(), 8);
let edges = bodies[0]["edges"].as_array().unwrap();
assert_eq!(edges.len(), 18);
// Through the thickness: four box corners, the two hole seams.
assert_eq!(edges.iter().filter(|e| (e["length"].as_f64().unwrap() - 10.0).abs() < 1e-6).count(), 6);
let t = s.execute("geometry.tessellate", &json!({"body": "Body1", "tolerance": 0.05})).unwrap();
let per_face: Vec<u64> = t["faces"].as_array().unwrap().iter().map(|f| f["triangles"].as_u64().unwrap()).collect();
@@ -649,6 +746,148 @@ mod tests {
let wider = s.execute("geometry.bodies", &json!({})).unwrap();
assert!(wider[0]["volume"].as_f64().unwrap() > volume);
assert_eq!(wider[0]["faces"], bodies[0]["faces"]);
let names = |b: &Value| b[0]["edges"].as_array().unwrap().iter().map(|e| e["name"].clone()).collect::<Vec<_>>();
assert_eq!(names(&wider), names(&bodies));
assert_eq!(s.journal.len(), 2);
}
/// A meshed, defined model of body `body` (a hex block whose bottom face is named `bottom`)
/// with a set on it and one on its face `face`.
fn defined_model(body: &str, face: &str) -> Session {
let mut s = Session::default();
let cube = [[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0], [0, 0, 10], [10, 0, 10], [10, 10, 10], [0, 10, 10]];
let script = json!([
{"command": "mesh.block", "params": {"body": body, "kind": "hex8", "corners": cube, "divisions": [1, 1, 1], "faces": {"1": "bottom"}}},
{"command": "model.set.create", "params": {"name": "all", "geometry": [{"body": body}]}},
{"command": "model.set.create", "params": {"name": "hole", "geometry": [{"body": body, "face": face}]}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}}},
]);
s.run_script(&script).unwrap();
s
}
/// `opened` changes with another document (a sample, another design file, a new model) and
/// stays with an edit, a solve or the same design opened again: views frame on that change.
#[test]
fn the_open_document_changes_only_when_another_is_opened() {
let mut s = Session::default();
let start = s.opened();
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
let cantilever = s.opened();
assert_ne!(cantilever, start);
s.execute("solve.run", &json!({})).unwrap();
s.execute("model.material.create", &json!({"name": "Al", "elastic": {"type": "isotropic", "young": 70000, "poisson": 0.33}})).unwrap();
assert_eq!(s.opened(), cantilever, "edits and solves keep the document");
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
assert_ne!(s.opened(), cantilever, "a sample opened again is a fresh start");
let (_dir, path) = sample_design_file(&Plate::default());
let before = s.opened();
s.execute("geometry.open", &json!({"path": path})).unwrap();
let design = s.opened();
assert_ne!(design, before, "another design file");
s.execute("geometry.open", &json!({"path": path})).unwrap();
assert_eq!(s.opened(), design, "the same design opened again after an edit");
s.execute("geometry.open", &json!({"path": path, "model": "new"})).unwrap();
assert_ne!(s.opened(), design, "a new model");
}
#[test]
fn reopening_the_same_design_keeps_the_mesh_and_definitions() {
let (_dir, path) = sample_design_file(&Plate::default());
let mut probe = Session::default();
probe.execute("geometry.open", &json!({"path": path})).unwrap();
let faces = probe.execute("geometry.bodies", &json!({})).unwrap()[0]["faces"].clone();
let mut s = defined_model("Body1", faces[0]["name"].as_str().unwrap());
let before = s.model.clone();
let r = s.execute("geometry.open", &json!({"path": path})).unwrap();
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("kept"), Some(true)), "{r}");
assert_eq!(r["stale"], json!({"mesh_bodies": [], "sets": [], "seeds": []}));
assert_eq!(s.model, before);
}
#[test]
fn a_different_design_starts_a_new_model_or_reports_what_is_stale() {
let (_dir, path) = sample_design_file(&Plate::default());
let defined = defined_model("Seal", "no-such-face");
let before = defined.model.clone();
assert!(!before.elements().is_empty() && before.sets().len() == 2);
// Kept (the default): nothing is lost, and the reply names what no longer resolves.
let mut kept = defined.clone();
let r = kept.execute("geometry.open", &json!({"path": path})).unwrap();
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("kept"), Some(false)), "{r}");
assert_eq!(r["stale"], json!({"mesh_bodies": ["Seal"], "sets": ["all", "hole"], "seeds": []}));
assert_eq!(kept.model, before);
// New: the mesh and every definition go, the units stay; one undo brings them back.
let mut fresh = defined.clone();
fresh.execute("model.units", &json!({"system": "m-kg-s-N-Pa"})).unwrap();
let units = fresh.model.units();
let before = fresh.model.clone();
let r = fresh.execute("geometry.open", &json!({"path": path, "model": "new"})).unwrap();
assert_eq!((r["model"].as_str(), r["related"].as_bool()), (Some("new"), Some(false)), "{r}");
assert_eq!(r["stale"], json!({"mesh_bodies": [], "sets": [], "seeds": []}));
assert!(fresh.model.elements().is_empty() && fresh.model.nodes().is_empty());
assert!(fresh.model.definition_counts().iter().all(|(_, n)| *n == 0));
assert_eq!(fresh.model.units(), units);
assert!(fresh.design.is_some());
fresh.execute("edit.undo", &json!({})).unwrap();
assert_eq!(fresh.model, before);
assert!(fresh.design.is_none());
// A bad choice changes nothing.
let mut s = defined.clone();
assert!(s.execute("geometry.open", &json!({"path": path, "model": "discard"})).is_err());
assert!(s.design.is_none() && s.model == defined.model);
}
#[test]
fn a_new_model_is_untitled_and_undo_brings_the_file_back() {
let (dir, design) = sample_design_file(&Plate::default());
let file = dir.0.join("a.fieldcraft").to_string_lossy().into_owned();
let mut s = defined_model("Seal", "no-such-face");
s.execute("file.save_as", &json!({"path": file})).unwrap();
assert!(!s.is_dirty());
s.execute("geometry.open", &json!({"path": design, "model": "new"})).unwrap();
assert_eq!(s.path, None, "a new model must not save over the old model's file");
assert!(s.is_dirty());
assert!(s.execute("file.save", &json!({})).is_err(), "save asks for a file");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.path.as_deref(), Some(file.as_str()));
assert!(!s.is_dirty(), "undo returns to the saved state of the old file");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.path, None);
assert!(s.is_dirty());
// Saving the new model and then editing it: undoing the edit keeps the new file.
let b = dir.0.join("b.fieldcraft").to_string_lossy().into_owned();
s.execute("file.save_as", &json!({"path": b})).unwrap();
s.execute("model.material.create", &json!({"name": "Al", "elastic": {"type": "isotropic", "young": 70000, "poisson": 0.33}})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.path.as_deref(), Some(b.as_str()));
assert!(!s.is_dirty());
// Undoing the open after that save returns to the old file; redo to the saved new one.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.path.as_deref(), Some(file.as_str()));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.path.as_deref(), Some(b.as_str()));
assert!(!s.is_dirty());
}
#[test]
fn keeping_the_model_keeps_its_file_and_a_sample_has_none() {
let (dir, design) = sample_design_file(&Plate::default());
let file = dir.0.join("a.fieldcraft").to_string_lossy().into_owned();
let mut s = defined_model("Seal", "no-such-face");
s.execute("file.save_as", &json!({"path": file})).unwrap();
s.execute("geometry.open", &json!({"path": design})).unwrap();
assert_eq!(s.path.as_deref(), Some(file.as_str()));
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
assert_eq!(s.path, None, "a sample must not save over the last opened file");
assert!(s.execute("file.save", &json!({})).is_err());
}
}
+180
View File
@@ -0,0 +1,180 @@
//! The log file: what the desktop app logs (through the `log` facade) goes to
//! `<data folder>/logs/fieldcraft.log`, one line per record:
//! `2026-10-14T10:03:22Z WARN [4242] fieldcraft_engine: message`. Warnings and errors also go to
//! the standard error stream.
//!
//! Bounded: past [`MAX_BYTES`] the file becomes `fieldcraft.log.1` (replacing the one before) and
//! a new one starts, so the logs never take more than twice that. A record is cut at
//! [`MAX_LINE`] bytes. The process id on every line lets a crash report take only the lines of
//! the run that crashed ([`tail`]), even when two apps share the file.
//!
//! Nothing is installed in tests, the CLI or the web build (which logs to the browser console).
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
/// The log file's name.
pub const FILE_NAME: &str = "fieldcraft.log";
/// The log file's size limit.
pub const MAX_BYTES: u64 = 2 << 20;
/// A record's size limit.
pub const MAX_LINE: usize = 4 << 10;
struct FileLogger {
path: PathBuf,
level: log::LevelFilter,
out: Mutex<Out>,
}
struct Out {
file: Option<File>,
bytes: u64,
}
static LOGGER: OnceLock<FileLogger> = OnceLock::new();
/// Send the `log` records at `level` and above to the log file in `dir` (created if needed).
/// Returns the file's path. Call once; later calls change nothing.
pub fn install(dir: &Path, level: log::LevelFilter) -> Result<PathBuf, String> {
fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let path = dir.join(FILE_NAME);
let file = open(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let bytes = file.metadata().map_or(0, |m| m.len());
let logger = FileLogger { path: path.clone(), level, out: Mutex::new(Out { file: Some(file), bytes }) };
if LOGGER.set(logger).is_err() {
return Err("a log file is already installed".into());
}
if let Some(l) = LOGGER.get() {
log::set_logger(l).map_err(|e| e.to_string())?;
log::set_max_level(level);
}
Ok(path)
}
fn open(path: &Path) -> std::io::Result<File> {
OpenOptions::new().create(true).append(true).open(path)
}
/// The log file, once [`install`]ed.
pub fn path() -> Option<&'static Path> {
LOGGER.get().map(|l| l.path.as_path())
}
/// The last `max` bytes of the log file's lines written by process `pid` (every line when
/// `None`), from the rotated file too when the current one is short. `None` without a log file.
pub fn tail(pid: Option<u32>, max: usize) -> Option<String> {
let path = path().map(Path::to_path_buf).or_else(default_path)?;
Some(tail_of(&path, pid, max))
}
/// [`tail`] of the log file at `path`.
fn tail_of(path: &Path, pid: Option<u32>, max: usize) -> String {
let mut text = String::new();
for p in [rotated(path), path.to_path_buf()] {
// The whole file (it is bounded): another process's lines may come between.
text.push_str(&read_end(&p, MAX_BYTES));
}
let mark = pid.map(|p| format!(" [{p}] "));
let mut lines: Vec<&str> = text.lines().filter(|l| mark.as_deref().is_none_or(|m| l.contains(m))).collect();
let mut total = 0;
let mut keep = lines.len();
for (i, l) in lines.iter().enumerate().rev() {
total += l.len() + 1;
if total > max {
break;
}
keep = i;
}
lines.drain(..keep);
lines.join("\n")
}
/// The log file of this computer's app (for a crash report written before [`install`]).
fn default_path() -> Option<PathBuf> {
fieldcraft_io::recovery::data_dir().map(|d| d.join("logs").join(FILE_NAME))
}
/// The file the log rotates into.
pub fn rotated(path: &Path) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(".1");
PathBuf::from(s)
}
/// The last `max` bytes of a file, from the start of a line.
fn read_end(path: &Path, max: u64) -> String {
let Ok(mut f) = File::open(path) else { return String::new() };
let len = f.metadata().map_or(0, |m| m.len());
let from = len.saturating_sub(max);
let mut buf = Vec::new();
if f.seek(SeekFrom::Start(from)).is_err() || f.take(max).read_to_end(&mut buf).is_err() {
return String::new();
}
let text = String::from_utf8_lossy(&buf).into_owned();
match (from > 0, text.find('\n')) {
(true, Some(i)) => text.get(i + 1..).unwrap_or_default().to_string(),
_ => text,
}
}
impl log::Log for FileLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.level() <= self.level
}
fn log(&self, record: &log::Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
let message = crate::crash::limited(&record.args().to_string(), MAX_LINE).replace('\n', "\n ");
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
let line = format!("{} {:<5} [{}] {}: {message}\n", crate::crash::utc(now), record.level(), std::process::id(), record.target());
if record.level() <= log::Level::Warn {
eprint!("{line}");
}
let Ok(mut out) = self.out.lock() else { return };
if out.bytes + line.len() as u64 > MAX_BYTES {
out.file = None;
let _ = fs::rename(&self.path, rotated(&self.path));
out.file = open(&self.path).ok();
out.bytes = 0;
}
if let Some(f) = &mut out.file
&& f.write_all(line.as_bytes()).is_err()
{
out.file = None;
}
out.bytes += line.len() as u64;
}
fn flush(&self) {
if let Ok(mut out) = self.out.lock()
&& let Some(f) = &mut out.file
{
let _ = f.flush();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tail_keeps_one_process_and_the_end() {
let d = std::env::temp_dir().join(format!("fieldcraft-logtail-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
let p = d.join(FILE_NAME);
fs::write(rotated(&p), "t INFO [7] a: old seven\nt INFO [8] a: old eight\n").unwrap();
fs::write(&p, "t INFO [7] a: one\nt WARN [8] a: other\nt INFO [7] a: two\n").unwrap();
assert_eq!(tail_of(&p, Some(7), 1000), "t INFO [7] a: old seven\nt INFO [7] a: one\nt INFO [7] a: two");
assert_eq!(tail_of(&p, Some(7), 40), "t INFO [7] a: one\nt INFO [7] a: two");
assert_eq!(tail_of(&p, None, 1000).lines().count(), 5);
// From the middle of a line, the partial line is dropped.
assert_eq!(read_end(&p, 20), "t INFO [7] a: two\n");
let _ = fs::remove_dir_all(&d);
}
}
+244
View File
@@ -0,0 +1,244 @@
//! Where the model is in the analysis workflow: the setup checklist ([`Session::progress`]).
//!
//! The stages run in the usual order — geometry, preparation, mesh, material, section, sets,
//! boundary conditions, loads, step, solve, results — each with whether it is done, the next one
//! to do, still to do, blocked (its command cannot run yet) or optional, and the command that
//! provides it. It is a guide, never a gate: a script can define things in any order, and
//! [`crate::requirement`] still decides what each command needs.
//!
//! Each stage is a [`Requirement`] check (a count), and Solve also reads the model check's first
//! error, so the whole list costs one [`fieldcraft_model::Model::check`]: the desktop reads it
//! once per model change, and `model.check` returns it as `progress`.
use fieldcraft_model::{Procedure, Severity};
use serde::Serialize;
use serde_json::{Value, json};
use crate::Session;
use crate::requirement::Requirement;
/// A step of the analysis workflow, in order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Stage {
Geometry,
/// Seeds and partitions that steer the mesh (optional).
Prepare,
Mesh,
Material,
Section,
Sets,
BoundaryConditions,
Loads,
Step,
Solve,
Results,
}
impl Stage {
pub const ALL: [Stage; 11] = [
Stage::Geometry,
Stage::Prepare,
Stage::Mesh,
Stage::Material,
Stage::Section,
Stage::Sets,
Stage::BoundaryConditions,
Stage::Loads,
Stage::Step,
Stage::Solve,
Stage::Results,
];
pub fn label(self) -> &'static str {
match self {
Stage::Geometry => "Geometry",
Stage::Prepare => "Seeds & partitions",
Stage::Mesh => "Mesh",
Stage::Material => "Material",
Stage::Section => "Section",
Stage::Sets => "Sets",
Stage::BoundaryConditions => "Boundary conditions",
Stage::Loads => "Loads",
Stage::Step => "Step",
Stage::Solve => "Solve",
Stage::Results => "Results",
}
}
/// What it checks; its provider is the command the stage starts.
fn requirement(self) -> Requirement {
match self {
Stage::Geometry => Requirement::Geometry,
Stage::Prepare => Requirement::Seed,
Stage::Mesh => Requirement::Analysable,
Stage::Material => Requirement::Material,
Stage::Section => Requirement::Section,
Stage::Sets => Requirement::Set,
Stage::BoundaryConditions => Requirement::BoundaryCondition,
Stage::Loads => Requirement::Load,
Stage::Step => Requirement::Step,
Stage::Solve => Requirement::Result,
Stage::Results => Requirement::ResultsShown,
}
}
}
/// Where a stage is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Done,
/// The first stage still to do.
Next,
/// Still to do after the next one; its command can already run.
Todo,
/// Its command cannot run yet (`detail` says why).
Blocked,
/// Not done, and not needed for this model.
Optional,
}
/// One row of the checklist.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StageState {
pub stage: Stage,
pub label: &'static str,
pub status: Status,
/// The command that does it.
pub command: &'static str,
/// Where that command is on the toolbar ("Properties › Material").
pub place: String,
/// Why it is blocked: what its command misses, or the model check's first error.
#[serde(skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
impl Session {
/// The setup checklist for the current model (one model check).
pub fn progress(&self) -> Vec<StageState> {
let first_error = self.model.check().into_iter().find(|d| d.severity == Severity::Error);
self.progress_given(first_error.map(|d| d.to_string()))
}
/// The checklist, given the model check's first error (`model.check` has run it already).
pub(crate) fn progress_given(&self, first_error: Option<String>) -> Vec<StageState> {
let m = &self.model;
let analysable = Requirement::Analysable.met(self);
// Models without elements (point masses, fluid domains) need no material or section.
let elementless = analysable && m.elements().is_empty();
let modal_only = !m.steps().is_empty() && m.steps().iter().all(|st| matches!(st.procedure, Procedure::Frequency { .. }));
let mut next_given = false;
Stage::ALL
.into_iter()
.map(|stage| {
let r = stage.requirement();
let done = r.met(self) || (stage == Stage::Geometry && analysable);
let optional = match stage {
Stage::Prepare => true,
Stage::Material | Stage::Section => elementless,
Stage::Loads => modal_only,
_ => false,
};
let command = r.provider();
let blocked = match crate::find_command(command).map(|spec| self.availability(spec)) {
Some(Err(u)) => Some(u.lines()),
_ if stage == Stage::Solve => first_error.clone(),
_ => None,
};
let (status, detail) = if done {
(Status::Done, None)
} else if optional {
(Status::Optional, None)
} else if blocked.is_some() {
next_given = true;
(Status::Blocked, blocked)
} else if next_given {
(Status::Todo, None)
} else {
next_given = true;
(Status::Next, None)
};
StageState { stage, label: stage.label(), status, command, place: r.place(), detail }
})
.collect()
}
}
/// The checklist as JSON, with the next stage's command first for agents:
/// `{"next": {"stage", "command"} | null, "stages": [...]}`.
pub fn to_json(stages: &[StageState]) -> Value {
let next = stages.iter().find(|s| matches!(s.status, Status::Next | Status::Blocked));
json!({
"next": next.map(|s| json!({"stage": s.stage, "command": s.command, "status": s.status, "detail": s.detail})),
"stages": stages,
})
}
#[cfg(test)]
mod tests {
use super::*;
use Status::*;
fn statuses(s: &Session) -> Vec<(Stage, Status)> {
s.progress().into_iter().map(|st| (st.stage, st.status)).collect()
}
fn status(s: &Session, stage: Stage) -> Status {
statuses(s).into_iter().find(|(st, _)| *st == stage).map(|(_, st)| st).unwrap()
}
#[test]
fn empty_model_starts_with_geometry() {
let s = Session::default();
let p = s.progress();
assert_eq!(p.len(), Stage::ALL.len());
assert_eq!((p[0].stage, p[0].status, p[0].command), (Stage::Geometry, Next, "geometry.open"));
assert_eq!(status(&s, Stage::Prepare), Optional);
// Meshing needs geometry; solving needs a mesh.
assert_eq!(status(&s, Stage::Mesh), Blocked);
assert!(p[2].detail.as_deref().is_some_and(|d| d.contains("geometry")));
assert_eq!(status(&s, Stage::Material), Todo);
assert_eq!(status(&s, Stage::Solve), Blocked);
assert_eq!(statuses(&s).iter().filter(|(_, st)| *st == Next).count(), 1);
}
#[test]
fn a_meshed_model_asks_for_its_material_next() {
let mut s = Session::default();
let cube = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
s.execute("mesh.block", &json!({"body": "B", "kind": "hex8", "corners": cube, "divisions": [1, 1, 1]})).unwrap();
assert_eq!(status(&s, Stage::Geometry), Done);
assert_eq!(status(&s, Stage::Mesh), Done);
assert_eq!(status(&s, Stage::Material), Next);
assert_eq!(status(&s, Stage::Section), Blocked);
assert_eq!(status(&s, Stage::Step), Todo);
}
#[test]
fn a_defined_model_is_ready_to_solve_then_to_show_results() {
let mut s = Session::default();
crate::cmd::solve::tests::cantilever(&mut s);
let before = statuses(&s);
for (stage, st) in &before[..9] {
assert!(matches!(st, Done | Optional), "{stage:?} {st:?}");
}
assert_eq!(status(&s, Stage::Solve), Next);
assert_eq!(to_json(&s.progress())["next"]["command"], "solve.run");
s.execute("solve.run", &json!({})).unwrap();
// A solve shows its results.
assert!(statuses(&s).iter().all(|(_, st)| matches!(st, Done | Optional)));
assert!(to_json(&s.progress())["next"].is_null());
s.execute("results.clear", &json!({})).unwrap();
assert_eq!(status(&s, Stage::Solve), Done);
assert_eq!((status(&s, Stage::Results), to_json(&s.progress())["next"]["command"].clone()), (Next, json!("results.contour")));
}
#[test]
fn model_check_returns_the_checklist() {
let mut s = Session::default();
let v = s.execute("model.check", &json!({})).unwrap();
assert_eq!(v["progress"]["next"]["command"], "geometry.open");
assert_eq!(v["progress"]["stages"].as_array().map(Vec::len), Some(Stage::ALL.len()));
}
}
+391
View File
@@ -0,0 +1,391 @@
//! What a command needs in the session before it can run: its [`Requirement`]s.
//!
//! Each [`crate::CommandSpec`] lists its requirements (`requires`) next to its id. A requirement
//! is something the command cannot run without — an open design to mesh, a material to give
//! plasticity to, a result to contour — never a workflow order: a script that builds a model step
//! by step meets each command's requirements as it goes.
//!
//! [`Session::execute`] checks them before running a command, so a command whose requirement is
//! missing fails at once, with no partial work, naming each missing piece and the toolbar entry
//! that provides it ([`Unavailable`]). The desktop UI reads the same check
//! ([`Session::availability`]) to grey the ribbon buttons, the command search and Solve, with the
//! same text as their tooltip. Every check is a count or a few comparisons, cheap enough to run
//! for every button on every frame.
use serde::Serialize;
use crate::{CommandSpec, Session, catalogue};
/// Something a command needs in the session.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Requirement {
/// An open SolidCraft design (`geometry.open`).
Design,
/// Geometry to mesh: an open design or an imported surface.
Geometry,
/// A datum plane, axis or point.
Datum,
/// A datum plane (what a partition cuts by).
DatumPlane,
DatumAxis,
DatumPoint,
/// A partition of the design.
Partition,
/// An edge seed.
Seed,
/// At least one mesh node.
Nodes,
/// At least one element.
Mesh,
/// Something to analyse: elements, point masses or springs, or only fluid steps (whose
/// domains carry their own grid) — the model check's first rule.
Analysable,
/// A material for the elements: met when there is a material or no element.
ElementMaterial,
/// A section for the elements: met when there is a section or no element.
ElementSection,
Set,
/// A set or a reference point (what boundary conditions, masses and springs act on).
Target,
Material,
Section,
ReferencePoint,
Coupling,
Contact,
Tie,
Mass,
Spring,
BoundaryCondition,
Load,
FluidDomain,
Step,
/// A solved step's result (current or stale).
Result,
/// Results on the display.
ResultsShown,
}
impl Requirement {
/// Whether the session meets it.
pub fn met(self, s: &Session) -> bool {
let m = &s.model;
let has_elements = !m.elements().is_empty();
match self {
Requirement::Design => s.design.is_some(),
Requirement::Geometry => s.design.is_some() || !s.surfaces.is_empty(),
Requirement::Datum => !m.datums().is_empty(),
Requirement::DatumPlane => m.datums().values().any(|d| d.plane().is_some()),
Requirement::DatumAxis => m.datums().values().any(|d| d.axis().is_some()),
Requirement::DatumPoint => m.datums().values().any(|d| d.point().is_some()),
Requirement::Partition => !m.partitions().is_empty(),
Requirement::Seed => !m.seeds().is_empty(),
Requirement::Nodes => !m.nodes().is_empty(),
Requirement::Mesh => has_elements,
Requirement::Analysable => {
has_elements
|| !m.masses().is_empty()
|| !m.springs().is_empty()
|| (!m.steps().is_empty() && m.steps().iter().all(|st| st.procedure.fluid_domain().is_some()))
}
Requirement::ElementMaterial => !has_elements || !m.materials().is_empty(),
Requirement::ElementSection => !has_elements || !m.sections().is_empty(),
Requirement::Set => !m.sets().is_empty(),
Requirement::Target => !m.sets().is_empty() || !m.reference_points().is_empty(),
Requirement::Material => !m.materials().is_empty(),
Requirement::Section => !m.sections().is_empty(),
Requirement::ReferencePoint => !m.reference_points().is_empty(),
Requirement::Coupling => !m.couplings().is_empty(),
Requirement::Contact => !m.contacts().is_empty(),
Requirement::Tie => !m.ties().is_empty(),
Requirement::Mass => !m.masses().is_empty(),
Requirement::Spring => !m.springs().is_empty(),
Requirement::BoundaryCondition => !m.boundary_conditions().is_empty(),
Requirement::Load => !m.loads().is_empty(),
Requirement::FluidDomain => !m.fluid_domains().is_empty(),
Requirement::Step => !m.steps().is_empty(),
Requirement::Result => s.result_steps().next().is_some(),
Requirement::ResultsShown => s.results_view.is_some(),
}
}
/// What is missing, as a noun phrase ("a material").
pub fn what(self) -> &'static str {
match self {
Requirement::Design => "an open design",
Requirement::Geometry => "geometry (an open design or an imported surface)",
Requirement::Datum => "a datum",
Requirement::DatumPlane => "a datum plane",
Requirement::DatumAxis => "a datum axis",
Requirement::DatumPoint => "a datum point",
Requirement::Partition => "a partition",
Requirement::Seed => "an edge seed",
Requirement::Nodes => "mesh nodes",
Requirement::Mesh | Requirement::Analysable => "a mesh",
Requirement::ElementMaterial | Requirement::Material => "a material",
Requirement::ElementSection | Requirement::Section => "a section",
Requirement::Set => "a set",
Requirement::Target => "a set or a reference point",
Requirement::ReferencePoint => "a reference point",
Requirement::Coupling => "a coupling",
Requirement::Contact => "a contact",
Requirement::Tie => "a tie",
Requirement::Mass => "a point mass",
Requirement::Spring => "a spring or dashpot",
Requirement::BoundaryCondition => "a boundary condition",
Requirement::Load => "a load",
Requirement::FluidDomain => "a fluid domain",
Requirement::Step => "a step",
Requirement::Result => "a solved step",
Requirement::ResultsShown => "results on the display",
}
}
/// The command that provides it.
pub fn provider(self) -> &'static str {
match self {
Requirement::Design | Requirement::Geometry => "geometry.open",
Requirement::Datum | Requirement::DatumPlane => "geometry.datum",
Requirement::DatumAxis => "geometry.datum.axis",
Requirement::DatumPoint => "geometry.datum.point",
Requirement::Partition => "geometry.partition",
Requirement::Seed => "mesh.seed.edge",
Requirement::Nodes => "mesh.node.add",
Requirement::Mesh | Requirement::Analysable => "mesh.tet.generate",
Requirement::ElementMaterial | Requirement::Material => "model.material.create",
Requirement::ElementSection | Requirement::Section => "model.section.create",
Requirement::Set | Requirement::Target => "model.set.create",
Requirement::ReferencePoint => "model.reference_point.create",
Requirement::Coupling => "model.coupling.create",
Requirement::Contact => "interaction.contact.pair",
Requirement::Tie => "interaction.tie",
Requirement::Mass => "model.mass.create",
Requirement::Spring => "model.spring.create",
Requirement::BoundaryCondition => "model.boundary_condition.create",
Requirement::Load => "model.load.create",
Requirement::FluidDomain => "model.fluid_domain.create",
Requirement::Step => "model.step.create",
Requirement::Result => "solve.run",
Requirement::ResultsShown => "results.contour",
}
}
/// Where the provider is on the toolbar: "Properties › Material".
pub fn place(self) -> String {
let id = self.provider();
match catalogue::entry_of(id) {
Some(c) => format!("{} › {}", c.tab.label(), c.label),
None => id.to_string(),
}
}
}
impl crate::schema::Collection {
/// What an item of the collection is as a requirement: its [`Requirement::provider`] is the
/// command that makes one, which a form offers when a reference field has nothing to pick.
pub fn requirement(self) -> Requirement {
use crate::schema::Collection as C;
match self {
C::Set => Requirement::Set,
C::Material => Requirement::Material,
C::Section => Requirement::Section,
C::ReferencePoint => Requirement::ReferencePoint,
C::Coupling => Requirement::Coupling,
C::Contact => Requirement::Contact,
C::Tie => Requirement::Tie,
C::Mass => Requirement::Mass,
C::Spring => Requirement::Spring,
C::BoundaryCondition => Requirement::BoundaryCondition,
C::Load => Requirement::Load,
C::FluidDomain => Requirement::FluidDomain,
C::Step => Requirement::Step,
C::SolvedStep => Requirement::Result,
C::Body => Requirement::Design,
C::Datum => Requirement::Datum,
C::DatumPlane => Requirement::DatumPlane,
C::DatumAxis => Requirement::DatumAxis,
C::DatumPoint => Requirement::DatumPoint,
C::Partition => Requirement::Partition,
}
}
}
/// A requirement the session does not meet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Missing(pub Requirement);
impl std::fmt::Display for Missing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Needs {} — {}", self.0.what(), self.0.place())
}
}
/// Why a command cannot run now: every requirement it misses, in its spec's order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unavailable {
pub command: &'static str,
pub missing: Vec<Missing>,
}
impl std::fmt::Display for Unavailable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} cannot run yet. {}", self.command, self.joined("; "))
}
}
impl Unavailable {
fn joined(&self, separator: &str) -> String {
self.missing.iter().map(ToString::to_string).collect::<Vec<_>>().join(separator)
}
/// The missing pieces, one per line.
pub fn lines(&self) -> String {
self.joined("\n")
}
/// A hover text: `head`, then the missing pieces when there are any.
pub fn tip(head: &str, missing: Option<&Unavailable>) -> String {
match missing {
Some(u) => format!("{head}\n\n{}", u.lines()),
None => head.to_string(),
}
}
/// As JSON for the control channel and listings: `{"reason", "missing": [{"requirement",
/// "what", "provider", "place"}]}`.
pub fn to_json(&self) -> serde_json::Value {
let missing: Vec<serde_json::Value> = self
.missing
.iter()
.map(|Missing(r)| serde_json::json!({"requirement": r, "what": r.what(), "provider": r.provider(), "place": r.place()}))
.collect();
serde_json::json!({"reason": self.lines(), "missing": missing})
}
}
impl Session {
/// Whether `spec` can run now: `Err` names every requirement it misses.
pub fn availability(&self, spec: &CommandSpec) -> std::result::Result<(), Unavailable> {
let missing: Vec<Missing> = spec.requires.iter().filter(|r| !r.met(self)).map(|&r| Missing(r)).collect();
if missing.is_empty() { Ok(()) } else { Err(Unavailable { command: spec.id, missing }) }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{EngineError, commands};
use serde_json::json;
fn missing(s: &Session, id: &str) -> Vec<Requirement> {
let spec = crate::find_command(id).unwrap();
s.availability(spec).err().map(|u| u.missing.into_iter().map(|Missing(r)| r).collect()).unwrap_or_default()
}
/// Every command in an empty session is either available or names what it misses, with the
/// toolbar entry that provides it; and running one that misses something fails at once with
/// that same message, leaving the session as it was.
#[test]
fn every_command_in_an_empty_session_runs_or_names_what_it_misses() {
for spec in commands() {
let mut s = Session::default();
match s.availability(spec) {
Ok(()) => {}
Err(u) => {
assert!(!u.missing.is_empty(), "{}", spec.id);
for Missing(r) in &u.missing {
assert!(crate::find_command(r.provider()).is_some(), "{}: {r:?}", spec.id);
assert!(catalogue::entry_of(r.provider()).is_some(), "{}: {r:?} has no toolbar entry", spec.id);
assert!(!r.met(&s));
}
let journal = s.journal.len();
let e = s.execute(spec.id, &json!({})).unwrap_err();
assert_eq!(e, EngineError::Unavailable(u.clone()), "{}", spec.id);
assert!(e.to_string().contains("Needs "), "{e}");
assert_eq!(s.journal.len(), journal);
}
}
}
}
/// Each provider meets what it provides on its own: a requirement is never one its provider
/// itself cannot meet from an empty model (no circular greying).
#[test]
fn providers_are_not_greyed_by_what_they_provide() {
for spec in commands() {
for r in spec.requires {
let provider = crate::find_command(r.provider()).unwrap();
assert!(!provider.requires.contains(r), "{} provides {r:?} but requires it", provider.id);
}
}
}
/// A collection's requirement is met exactly when it has a name to pick, and its provider is
/// a command on the toolbar.
#[test]
fn collections_require_what_they_list() {
use crate::schema::Collection as C;
let all = [
C::Set,
C::Material,
C::Section,
C::ReferencePoint,
C::Coupling,
C::Contact,
C::Tie,
C::Mass,
C::Spring,
C::BoundaryCondition,
C::Load,
C::FluidDomain,
C::Step,
C::SolvedStep,
C::Body,
C::Datum,
C::DatumPlane,
C::DatumAxis,
C::DatumPoint,
C::Partition,
];
let empty = Session::default();
for c in all {
let r = c.requirement();
assert!(empty.names(c).is_empty() && !r.met(&empty), "{c:?}");
assert!(catalogue::entry_of(r.provider()).is_some(), "{c:?}");
}
let mut s = Session::default();
s.execute("model.material.create", &json!({"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}})).unwrap();
assert!(C::Material.requirement().met(&s) && s.names(C::Material) == ["Steel"]);
}
#[test]
fn targeted_requirements() {
let empty = Session::default();
assert_eq!(missing(&empty, "model.material.plasticity"), [Requirement::Material]);
assert_eq!(missing(&empty, "results.contour"), [Requirement::Result]);
assert_eq!(missing(&empty, "solve.static"), [Requirement::Analysable, Requirement::Step]);
assert_eq!(missing(&empty, "mesh.tet.generate"), [Requirement::Geometry]);
assert!(missing(&empty, "model.material.create").is_empty());
assert!(missing(&empty, "model.step.create").is_empty());
// Meshed, nothing defined: solving needs a material, a section and a step.
let mut meshed = Session::default();
let cube = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
meshed.execute("mesh.block", &json!({"body": "B", "kind": "hex8", "corners": cube, "divisions": [1, 1, 1]})).unwrap();
assert_eq!(missing(&meshed, "solve.static"), [Requirement::ElementMaterial, Requirement::ElementSection, Requirement::Step]);
let e = meshed.execute("solve.run", &json!({})).unwrap_err().to_string();
assert_eq!(
e,
"solve.run cannot run yet. Needs a material — Properties › Material; Needs a section — Properties › Section; Needs a step — Steps › Step"
);
// A defined, solved cantilever: everything a result needs is there.
let mut solved = Session::default();
crate::cmd::solve::tests::cantilever(&mut solved);
assert!(missing(&solved, "solve.run").is_empty());
solved.execute("solve.run", &json!({})).unwrap();
for id in ["results.contour", "results.deformed", "solve.probe", "results.clear", "model.material.plasticity"] {
assert!(missing(&solved, id).is_empty(), "{id}");
}
}
}
+86 -7
View File
@@ -87,10 +87,22 @@ pub enum Field {
Temperature,
/// Heat flux magnitude (heat transfer steps, at the end of the step).
HeatFlux,
/// Contact pressure (nonlinear static steps with contact: 0 off the contacts' secondary
/// surfaces).
ContactPressure,
/// The normalised contact gap of the secondary surfaces' nodes (negative: penetration).
ContactGap,
/// Contact status of the secondary surfaces' nodes: 0 open, 1 closed (frictionless) or
/// sticking, 2 slipping.
ContactStatus,
/// The magnitude of the friction's shear traction (0 off the secondary surfaces).
ContactShear,
/// The magnitude of the frictional slip over the last increment (secondary surfaces' nodes).
ContactSlip,
}
impl Field {
pub const ALL: [Field; 17] = [
pub const ALL: [Field; 22] = [
Field::Displacement,
Field::DisplacementX,
Field::DisplacementY,
@@ -108,6 +120,11 @@ impl Field {
Field::StressYz,
Field::Temperature,
Field::HeatFlux,
Field::ContactPressure,
Field::ContactGap,
Field::ContactStatus,
Field::ContactShear,
Field::ContactSlip,
];
/// The id commands take (`von_mises`…).
@@ -130,6 +147,11 @@ impl Field {
Field::StressYz => "stress_yz",
Field::Temperature => "temperature",
Field::HeatFlux => "heat_flux",
Field::ContactPressure => "contact_pressure",
Field::ContactGap => "contact_gap",
Field::ContactStatus => "contact_status",
Field::ContactShear => "contact_shear",
Field::ContactSlip => "contact_slip",
}
}
@@ -152,6 +174,11 @@ impl Field {
Field::StressYz => "Stress YZ",
Field::Temperature => "Temperature",
Field::HeatFlux => "Heat flux magnitude",
Field::ContactPressure => "Contact pressure",
Field::ContactGap => "Contact gap",
Field::ContactStatus => "Contact status (0 open, 1 closed or stick, 2 slip)",
Field::ContactShear => "Contact shear traction",
Field::ContactSlip => "Contact slip",
}
}
@@ -170,7 +197,12 @@ impl Field {
| Field::Velocity
| Field::Temperature
| Field::HeatFlux
)
) && !self.is_contact()
}
/// Whether it is a contact quantity.
pub fn is_contact(self) -> bool {
matches!(self, Field::ContactPressure | Field::ContactGap | Field::ContactStatus | Field::ContactShear | Field::ContactSlip)
}
/// Whether it is a heat transfer quantity.
@@ -181,6 +213,7 @@ impl Field {
/// The fields a result has: displacements everywhere, stresses for static steps and explicit
/// frames that kept them (mode shapes have no stress scale), velocity for explicit frames.
pub fn available(r: &StepResult) -> impl Iterator<Item = Field> + '_ {
let contact = matches!(r.kind(), Kind::Static(s) if !s.contacts.is_empty());
let (stress, velocity, temperature, flux) = match r.kind() {
Kind::Static(s) => (true, false, s.temperature.is_some(), false),
Kind::Frequency(_) => (false, false, false, false),
@@ -197,6 +230,7 @@ impl Field {
Field::Velocity => velocity,
Field::Temperature => temperature,
Field::HeatFlux => flux,
f if f.is_contact() => contact,
f => stress || !f.is_stress(),
})
.collect::<Vec<_>>()
@@ -234,9 +268,11 @@ pub struct ResultsView {
}
impl ResultsView {
/// How a step's result is shown first: deformed, with von Mises contours for a static step
/// (and an explicit step that kept stresses), the first mode with displacement contours for
/// a frequency step; an explicit step at its last frame, to true scale.
/// How a step's result is shown first: a static step undeformed with von Mises contours, so
/// they are read on the true geometry (`results.deformed` shows the deformed shape, at the
/// automatic scale); a frequency step's first mode deformed with displacement contours (a
/// mode shape is a deformation); an explicit step at its last frame, deformed to true scale
/// (with von Mises contours when it kept stresses); a heat step undeformed.
pub fn for_result(r: &StepResult) -> ResultsView {
let heat = matches!(r.kind(), Kind::Heat(_));
let contour = if heat {
@@ -249,7 +285,7 @@ impl ResultsView {
let scale = matches!(r.kind(), Kind::Explicit(_)).then_some(1.0);
ResultsView {
step: r.step().to_string(),
deformed: !heat,
deformed: matches!(r.kind(), Kind::Frequency(_) | Kind::Explicit(_)),
scale,
contour: Some(contour),
bands: DEFAULT_BANDS,
@@ -333,6 +369,10 @@ pub fn field_values(model: &Model, r: &StepResult, field: Field, pick: Pick) ->
Kind::Heat(h) => Ok(h.flux.iter().map(|v| magnitude(*v)).collect()),
_ => Err(unavailable()),
},
Field::ContactPressure | Field::ContactGap | Field::ContactStatus | Field::ContactShear | Field::ContactSlip => match r.kind() {
Kind::Static(s) if !s.contacts.is_empty() => Ok(contact_values(s, field)),
_ => Err(unavailable()),
},
Field::VonMises => each(&fieldcraft_fem::von_mises),
Field::MaxPrincipal => principal(0),
Field::MidPrincipal => principal(1),
@@ -346,6 +386,45 @@ pub fn field_values(model: &Model, r: &StepResult, field: Field, pick: Pick) ->
}
}
/// A contact field at every node of a static result: the largest pressure, shear, slip or status
/// code, or the smallest gap, over the contacts a node is a secondary node of; off them 0
/// pressure and shear, and no gap, status or slip (NaN).
fn contact_values(s: &StaticResult, field: Field) -> Vec<f64> {
use fieldcraft_solver::contact::Status;
let zero = matches!(field, Field::ContactPressure | Field::ContactShear);
let mut out = vec![if zero { 0.0 } else { f64::NAN }; s.nodes.len()];
let larger = |v: &mut f64, x: f64| *v = if v.is_nan() { x } else { v.max(x) };
for c in &s.contacts {
for (k, label) in c.nodes.iter().enumerate() {
let Some(v) = s.nodes.binary_search(label).ok().and_then(|i| out.get_mut(i)) else { continue };
match field {
Field::ContactPressure => larger(v, c.pressure.get(k).copied().unwrap_or(0.0)),
Field::ContactShear => larger(v, c.shear.get(k).map_or(0.0, |t| magnitude(*t))),
Field::ContactSlip => {
if let Some(g) = c.slip.get(k) {
larger(v, magnitude(*g));
}
}
Field::ContactGap => {
if let Some(Some(g)) = c.gap.get(k) {
*v = if v.is_nan() { *g } else { v.min(*g) };
}
}
Field::ContactStatus => {
let code = match c.status.get(k) {
Some(Status::Closed | Status::Stick) => 1.0,
Some(Status::Slip) => 2.0,
Some(Status::Open) | None => 0.0,
};
larger(v, code);
}
_ => {}
}
}
}
out
}
/// Element values (in `elements` order) averaged at the nodes (in `nodes` order) of the
/// elements around them; a node no element reaches gets NaN.
fn nodal_average(model: &Model, nodes: &[u32], elements: &[u32], values: &[[f64; 6]]) -> Vec<[f64; 6]> {
@@ -472,7 +551,7 @@ mod tests {
}
let (modes, _) = s.latest_result("Modes").unwrap();
assert_eq!(Field::available(modes).count(), 4);
assert_eq!(Field::available(bend).count(), Field::ALL.len() - 3, "all but velocity and the thermal fields");
assert_eq!(Field::available(bend).count(), Field::ALL.len() - 8, "all but velocity, the thermal and the contact fields");
assert!(field_values(&s.model, modes, Field::VonMises, Pick { mode: 1, frame: None }).is_err());
assert!(field_values(&s.model, modes, Field::Displacement, Pick { mode: 9, frame: None }).is_err());
assert_eq!(field_values(&s.model, modes, Field::Displacement, Pick { mode: 2, frame: None }).unwrap().len(), modes.nodes().len());
+664 -4
View File
@@ -9,7 +9,13 @@
//! [`cantilever`], a model ready to solve: a steel beam clamped at one end with a load on the
//! other, a static and a frequency step. [`impact`]: the same beam flying onto a rigid wall, an
//! explicit dynamic step.
//!
//! The examples gallery (docs/examples.md), each ready to solve with `solve.run`:
//! [`drop_test`], [`rubber_seal`], [`flow_past`], [`heated_bracket`], [`bracket_hex`] and [`crank_arm`]. Their
//! geometry is a SolidCraft script run when the sample opens ([`Sample::design`]): a corpus
//! recipe (`tests/corpus`) or [`UPRIGHT_BRACKET`].
use fieldcraft_geometry::Shape;
use serde_json::{Value, json};
/// A sample the app offers (Help › Samples, the empty viewport, `file.sample`, `--sample NAME`).
@@ -18,23 +24,97 @@ pub struct Sample {
pub label: &'static str,
/// One line: what it shows.
pub about: &'static str,
pub script: fn() -> Value,
/// The SolidCraft script (`{"commands": [...]}`, the corpus recipe form) that builds the
/// sample's geometry, opened as its design before [`Sample::script`] runs.
pub design: Option<&'static str>,
/// Commands run on the opened design before [`Sample::script`] (datums and partitions), so
/// the script is given the bodies as they cut it.
pub prepare: Option<fn() -> Value>,
/// The model's commands, given the design's bodies (none without a design).
pub script: fn(&[Shape]) -> Value,
}
/// Every sample, the default first.
pub const SAMPLES: &[Sample] = &[
Sample { name: "parts", label: "Hex and Tet Parts", about: "A hex8 block beside a tet4 cube: meshes to look at, nothing to solve", script },
Sample {
name: "parts",
label: "Hex and Tet Parts",
about: "A hex8 block beside a tet4 cube: meshes to look at, nothing to solve",
design: None,
prepare: None,
script: |_| script(),
},
Sample {
name: "cantilever",
label: "Cantilever",
about: "A clamped steel beam with an end load: a static and a frequency step, ready to solve",
script: cantilever,
design: None,
prepare: None,
script: |_| cantilever(),
},
Sample {
name: "impact",
label: "Bar Impact",
about: "The steel beam flying onto a rigid wall: an explicit dynamic step, ready to solve",
script: impact,
design: None,
prepare: None,
script: |_| impact(),
},
Sample {
name: "drop-test",
label: "Drop Test",
about: "An aluminium L-bracket dropped 2 m onto a tilted rigid floor: explicit dynamics, the strike and its stress waves",
design: Some(UPRIGHT_BRACKET),
prepare: None,
script: |_| drop_test(),
},
Sample {
name: "rubber-seal",
label: "Rubber Seal",
about: "A rubber gasket ring squeezed 25 % between bonded plates: nonlinear static, Mooney–Rivlin, large strain",
design: None,
prepare: None,
script: |_| rubber_seal(),
},
Sample {
name: "flow-past",
label: "Flow Past a Bracket",
about: "Air flowing past an L-bracket on the floor: lattice Boltzmann flow and the force on each face",
design: Some(UPRIGHT_BRACKET),
prepare: None,
script: |_| flow_past(),
},
Sample {
name: "heated-bracket",
label: "Heated Bracket",
about: "A steel bracket clamped at its holes and heated at one end: steady heat conduction and the thermal stress",
design: Some(FILLETED_BRACKET),
prepare: None,
script: |_| heated_bracket(),
},
Sample {
name: "bracket-hex",
label: "Hex-Meshed Bracket",
about: "The filleted bracket split into 30 cells and meshed all-hex (hex20): clamped, loaded, von Mises",
design: Some(PARTITIONED_BRACKET),
prepare: None,
script: bracket_hex,
},
Sample {
name: "crank-mirror",
label: "Mirrored Crank Arm",
about: "The crank arm of crank-arm under the name of its mirror workflow: a partitioned half meshed structured all-hex (hex20) and mirrored into one conforming mesh",
design: Some(CRANK_ARM),
prepare: Some(crank_prepare),
script: crank_arm,
},
Sample {
name: "crank-arm",
label: "Bicycle Crank Arm",
about: "An aluminium bicycle crank meshed structured all-hex (hex20) from a partitioned half and its mirror image: square bore fixed, a rider's weight on the pedal, von Mises",
design: Some(CRANK_ARM),
prepare: Some(crank_prepare),
script: crank_arm,
},
];
@@ -210,6 +290,303 @@ pub fn impact() -> Value {
Value::Array(steps)
}
/// An L-bracket standing on its foot, Z up, as a SolidCraft script: a 60 × 40 mm foot and a 50 mm
/// upright, both 8 mm thick, with an R6 fillet inside the bend (the corpus `filleted-bracket`'s
/// profile without its holes, sketched on XZ so it sweeps along y). Body `Bracket`; its faces
/// `F2:side:l1` (the foot's underside, z = 0), `l2` (the foot's end, x = 60), `l3` (the foot's top),
/// `l4` (the upright's inside, x = 8), `l5` (the upright's top, z = 50) and `l6` (its back, x = 0).
pub const UPRIGHT_BRACKET: &str = r#"{"commands": [
{"command": "sketch.create", "params": {"plane": "XZ", "name": "Profile"}},
{"command": "sketch.line", "params": {"points": [[0, 0], [60, 0], [60, -8], [8, -8], [8, -50], [0, -50]], "closed": true}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.extrude", "params": {"distance": 40, "body_name": "Bracket"}},
{"command": "solid.fillet", "params": {"edges": [[8, 20, 8]], "radius": 6}}
]}"#;
/// Aluminium (E = 70 GPa, ν = 0.33, ρ = 2.7 t/m³, yield 240 MPa with 700 MPa linear hardening),
/// in mm, t, s, N, MPa.
fn aluminium(name: &str) -> Value {
json!({"command": "model.material.create", "params": {"name": name, "elastic": {"type": "isotropic", "young": 70000, "poisson": 0.33}, "density": 2.7e-9,
"plastic": {"type": "bilinear", "yield_stress": 240, "hardening_modulus": 700, "hardening": "isotropic"}}})
}
/// Standard gravity, mm/s².
pub const GRAVITY: f64 = 9810.0;
/// The drop test's height of fall, mm: the bracket meets the floor at √(2 g h) = 6.26 m/s.
pub const DROP_HEIGHT: f64 = 2000.0;
/// The drop test's floor tilt about y, degrees: the foot's end strikes first.
const DROP_TILT: f64 = 15.0;
/// [`UPRIGHT_BRACKET`] in aluminium, hex8 elements swept 3 mm (one-point, stiffness hourglass
/// control), falling at √(2 g h) onto a rigid floor tilted 15° so the foot's end lands first,
/// 0.1 mm below that corner; gravity on. Step `Drop` (explicit dynamics, 1 ms: the strike, the
/// stress waves through the bend and the bracket pivoting onto its foot; 20 field frames, the
/// upright's top (set `top`) in the histories).
pub fn drop_test() -> Value {
let speed = (2.0 * GRAVITY * DROP_HEIGHT).sqrt();
let tilt = DROP_TILT.to_radians();
let step = json!({
"type": "explicit_dynamic", "end_time": 1e-3, "output_interval": 5e-5, "history_interval": 5e-6, "history_nodes": "top",
"initial_velocities": [{"set": "bracket", "velocity": [0, 0, -speed]}],
"rigid_walls": [{"set": "bracket", "point": [60, 0, -0.1], "normal": [-tilt.sin(), 0, tilt.cos()]}],
"hourglass": {"type": "stiffness", "coefficient": 0.05}
});
json!([
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
{"command": "mesh.hex.generate", "params": {"body": "Bracket", "size": 3, "method": "extrude"}},
{"command": "model.set.create", "params": {"name": "bracket", "geometry": [{"body": "Bracket"}]}},
{"command": "model.set.create", "params": {"name": "top", "geometry": [{"body": "Bracket", "face": "F2:side:l5"}]}},
aluminium("Aluminium"),
{"command": "model.section.create", "params": {"name": "Bracket", "set": "bracket", "material": "Aluminium", "kind": {"type": "solid"}, "formulation": {"integration": "reduced"}}},
{"command": "model.load.create", "params": {"name": "Gravity", "type": "gravity", "acceleration": [0, 0, -GRAVITY]}},
{"command": "model.step.create", "params": {"name": "Drop", "procedure": step, "loads": ["Gravity"]}},
])
}
/// The rubber seal: inner and outer radius and height of the ring (mm), and how far it is squeezed.
pub const SEAL: [f64; 3] = [20.0, 30.0, 10.0];
pub const SEAL_SQUEEZE: f64 = 2.5;
/// A rubber gasket ring ([`SEAL`]: 20 mm inside radius, 30 mm outside, 10 mm high) of hybrid hex8
/// elements, four mapped quarter blocks with arc edges (body `Seal`, block faces `bottom` and
/// `top`), squeezed by [`SEAL_SQUEEZE`] (25 %) between plates bonded to it: `bottom` fixed, `top`
/// moved down with its in-plane motion held. Generic rubber: E = 6 MPa, ν = 0.49, Mooney–Rivlin
/// with C01 = 0.2 MPa (C10 = μ/2 − C01 = 0.81 MPa). Step `Squeeze` (nonlinear static).
pub fn rubber_seal() -> Value {
let [inner, outer, height] = SEAL;
let mut steps = vec![json!({"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}})];
for quarter in 0..4u8 {
let (a0, a1) = (f64::from(quarter) * std::f64::consts::FRAC_PI_2, f64::from(quarter + 1) * std::f64::consts::FRAC_PI_2);
let at = |r: f64, a: f64, z: f64| [r * a.cos(), r * a.sin(), z];
let corners = [
at(inner, a0, 0.0),
at(outer, a0, 0.0),
at(outer, a1, 0.0),
at(inner, a1, 0.0),
at(inner, a0, height),
at(outer, a0, height),
at(outer, a1, height),
at(inner, a1, height),
];
let arc = |a: u8, b: u8, z: f64| json!({"corners": [a, b], "arc": {"center": [0, 0, z]}});
steps.push(json!({"command": "mesh.block", "params": {
"body": "Seal", "kind": "hex8", "corners": corners, "divisions": [5, 10, 5],
"edges": [arc(1, 4, 0.0), arc(2, 3, 0.0), arc(5, 8, height), arc(6, 7, height)],
"faces": {"1": "bottom", "2": "top"}
}}));
}
steps.extend([
json!({"command": "model.set.create", "params": {"name": "seal", "geometry": [{"body": "Seal"}]}}),
json!({"command": "model.set.create", "params": {"name": "bottom", "geometry": [{"body": "Seal", "face": "bottom"}]}}),
json!({"command": "model.set.create", "params": {"name": "top", "geometry": [{"body": "Seal", "face": "top"}]}}),
json!({"command": "model.material.create", "params": {"name": "Rubber", "elastic": {"type": "isotropic", "young": 6, "poisson": 0.49}, "density": 1.1e-9,
"hyperelastic": {"type": "mooney_rivlin", "c01": 0.2}}}),
json!({"command": "model.section.create", "params": {"name": "Seal", "set": "seal", "material": "Rubber", "kind": {"type": "solid"}, "formulation": {"hybrid": true}}}),
json!({"command": "model.boundary_condition.create", "params": {"name": "Base", "type": "fixed", "target": {"set": "bottom"}}}),
json!({"command": "model.boundary_condition.create", "params": {"name": "Press", "type": "displacement", "target": {"set": "top"}, "values": [0, 0, -SEAL_SQUEEZE, null, null, null]}}),
json!({"command": "model.step.create", "params": {"name": "Squeeze", "procedure": {"type": "nonlinear_static", "initial_increment": 0.1}, "boundary_conditions": ["Base", "Press"]}}),
]);
Value::Array(steps)
}
/// The flow sample's free-stream speed, mm/s.
pub const FLOW_SPEED: f64 = 25.0;
/// Air at 20 °C: density (t/mm³) and dynamic viscosity (MPa s).
const AIR: [f64; 2] = [1.2e-12, 1.8e-11];
/// Air at [`FLOW_SPEED`] past [`UPRIGHT_BRACKET`] standing on the floor, the upright's back face
/// to the wind: a 240 × 120 × 100 mm box of 2.5 mm cells (184 320), a uniform inlet at x_min, an
/// outlet at zero pressure at x_max, a no-slip floor and slip walls at the sides and top. Reynolds
/// number ρ U h / μ = 83 on the upright's 50 mm height: laminar, a steady wake. Step `Flow` (16 s,
/// about 6.7 flow-throughs; ten frames) reports the force on each named face of the bracket.
pub fn flow_past() -> Value {
let [density, viscosity] = AIR;
json!([
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
{"command": "model.material.create", "params": {"name": "Air", "density": density, "fluid": {"type": "newtonian", "viscosity": viscosity}}},
{"command": "model.fluid_domain.create", "params": {
"name": "Wind", "material": "Air", "min": [-60, -40, 0], "max": [180, 80, 100], "spacing": 2.5,
"faces": {
"x_min": {"type": "velocity", "velocity": [FLOW_SPEED, 0, 0]}, "x_max": {"type": "pressure", "pressure": 0},
"y_min": {"type": "slip"}, "y_max": {"type": "slip"}, "z_min": {"type": "wall"}, "z_max": {"type": "slip"}
},
"obstacles": ["Bracket"], "initial_velocity": [FLOW_SPEED, 0, 0]
}},
{"command": "model.step.create", "params": {"name": "Flow", "procedure": {"type": "fluid", "domain": "Wind", "end_time": 16, "frames": 10}}},
])
}
/// The corpus filleted bracket (`tests/corpus/filleted-bracket`): an 8 mm L-bracket, foot along
/// x (60 mm) and upright along y (50 mm), extruded 40 mm along z, an R6 fillet, an 8 mm hole
/// through each leg (`F4` through the foot at x = 40, `F5` through the upright at y = 32).
pub const FILLETED_BRACKET: &str = include_str!("../../../tests/corpus/filleted-bracket/recipe.json");
/// The heated bracket: the heater's and the surrounding air's temperatures (°C, also the stress
/// free temperature), and steel's expansion coefficient (1/K).
pub const HEATER: f64 = 120.0;
pub const AMBIENT: f64 = 20.0;
pub const STEEL_EXPANSION: f64 = 1.2e-5;
/// [`FILLETED_BRACKET`] in steel (k = 50 W/(m K), α = 12 × 10⁻⁶/K, stress free at 20 °C), tet10
/// elements of 4 mm: its upright's end (`F2:side:l5`, set `hot`) held at [`HEATER`], the rest of
/// its outside (set `skin`) cooled by still air at [`AMBIENT`] (h = 10 W/(m² K)), both hole bores
/// clamped (set `holes`). Step `Heat` (coupled temperature–displacement, steady): the
/// temperature field and the stress of the expansion the clamps hold back. In mm, t, s, N, MPa:
/// k in mW/(mm K), h in mW/(mm² K).
pub fn heated_bracket() -> Value {
let face = |f: &str| json!({"body": "Bracket", "face": f});
let skin: Vec<Value> =
["F2:start", "F2:top", "F2:side:l1", "F2:side:l2", "F2:side:l3", "F2:side:l4", "F2:side:l6", "F3:blend:F2:side:l3|F2:side:l4"]
.into_iter()
.map(face)
.collect();
let holes: Vec<Value> = ["F4:bore:side:0", "F4:bore:side:1", "F5:bore:side:0", "F5:bore:side:1"].into_iter().map(face).collect();
json!([
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
{"command": "mesh.tet.generate", "params": {"body": "Bracket", "size": 4, "order": "quadratic", "tolerance": 0.05}},
{"command": "model.set.create", "params": {"name": "bracket", "geometry": [{"body": "Bracket"}]}},
{"command": "model.set.create", "params": {"name": "holes", "geometry": holes}},
{"command": "model.set.create", "params": {"name": "hot", "geometry": [face("F2:side:l5")]}},
{"command": "model.set.create", "params": {"name": "skin", "geometry": skin}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}, "density": 7.85e-9,
"thermal": {"conductivity": 50, "specific_heat": 4.6e8, "expansion": STEEL_EXPANSION, "reference_temperature": AMBIENT}}},
{"command": "model.section.create", "params": {"name": "Bracket", "set": "bracket", "material": "Steel", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "holes"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Heater", "type": "temperature", "target": {"set": "hot"}, "value": HEATER}},
{"command": "model.load.create", "params": {"name": "Air", "type": "convection", "set": "skin", "film": 0.01, "sink": AMBIENT}},
{"command": "model.step.create", "params": {"name": "Heat", "procedure": {"type": "coupled_temperature_displacement"}, "boundary_conditions": ["Clamp", "Heater"], "loads": ["Air"]}},
])
}
/// The corpus filleted bracket split into 30 cells (`tests/corpus/filleted-bracket-blocks`),
/// each a mapped block: the part `mesh.hex.blocks` meshes all-hex.
pub const PARTITIONED_BRACKET: &str = include_str!("../../../tests/corpus/filleted-bracket-blocks/recipe.json");
/// [`PARTITIONED_BRACKET`] meshed all-hex as one conforming mesh of hex20 elements of 3 mm, in
/// steel: the upright's end (`F2:side:l5` in every cell that has it, set `top`) clamped, 1 kN down
/// (−y) on the foot's end (`F2:side:l2`, set `tip`). Step `Load` (linear static). `bodies` are the
/// design's cells.
pub fn bracket_hex(bodies: &[Shape]) -> Value {
let faces = |name: &str| -> Vec<Value> {
bodies.iter().filter(|b| b.faces().iter().any(|f| f.name == name)).map(|b| json!({"body": b.name, "face": name})).collect()
};
let cells: Vec<Value> = bodies.iter().map(|b| json!({"body": b.name})).collect();
json!([
{"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}},
{"command": "mesh.hex.blocks", "params": {"size": 3, "order": 2}},
{"command": "model.set.create", "params": {"name": "bracket", "geometry": cells}},
{"command": "model.set.create", "params": {"name": "top", "geometry": faces("F2:side:l5")}},
{"command": "model.set.create", "params": {"name": "tip", "geometry": faces("F2:side:l2")}},
{"command": "model.material.create", "params": {"name": "Steel", "elastic": {"type": "isotropic", "young": 210000, "poisson": 0.3}, "density": 7.85e-9}},
{"command": "model.section.create", "params": {"name": "Bracket", "set": "bracket", "material": "Steel", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Clamp", "type": "fixed", "target": {"set": "top"}}},
{"command": "model.load.create", "params": {"name": "Push", "type": "force", "target": {"set": "tip"}, "vector": [0, -1000, 0]}},
{"command": "model.step.create", "params": {"name": "Load", "procedure": {"type": "static"}, "boundary_conditions": ["Clamp"], "loads": ["Push"]}},
])
}
/// The bicycle crank arm (`crates/engine/samples/crank-arm.json`): a 170 mm aluminium arm, 16 mm
/// thick and tapering from 38 to 24 mm, joined by tangent root arcs to a Ø46 × 22 spindle boss
/// with a 12.7 mm square bore (R1.5 corners) and a Ø30 × 20 pedal boss with a Ø14 hole, and an
/// 82 × 14 × 8 pocket in its back (R5 corners). Made to be swept all-hex by `mesh.hex.generate`
/// as a stack of extrusions along z: no pocket floor fillet or boss chamfers, and the root arcs
/// meet the bosses about 20° off tangent (tangent to a circle 0.5 mm inside each boss), since a
/// tangent meeting leaves a zero-angle cusp on the arm's top face.
pub const CRANK_ARM: &str = include_str!("../samples/crank-arm.json");
/// The crank arm's pedal load (N): a standing rider's weight on one pedal.
pub const PEDAL_LOAD: f64 = 1500.0;
/// The half of the crank [`crank_prepare`] cuts off on the symmetry plane (y < 0), the one
/// meshed; its mirror image is `CrankArm/b`.
pub const CRANK_HALF: &str = "CrankArm/a";
/// [`CRANK_ARM`] meshed structured all-hex (hex20 of 3 mm) from its half and mirrored, in
/// 6061-T6 aluminium: the square bore's faces and corner fillets (set `spindle`) fixed,
/// [`PEDAL_LOAD`] on the pedal hole (set `pedal`), in the crank's plane and across the arm (−y).
/// Step `Pedal` (linear static). The faces are picked by their surfaces, not their names: the
/// square bore's are the vertical planes 6.35 mm from the spindle axis and the R1.5 cylinders
/// beside it, the pedal hole is the Ø14 cylinder on the pedal axis.
///
/// The mesh: [`crank_prepare`] cuts the crank on its symmetry plane only; `mesh.hex.generate`
/// extrudes the half [`CRANK_HALF`], decomposing its cross-section into blocks itself (half
/// rings round both bores, the pocket's corners as triangle primitives, four-sided blocks along
/// the arm), with no seeds; `mesh.mirror` reflects it onto `CrankArm/b`, joined on the plane.
pub fn crank_arm(bodies: &[Shape]) -> Value {
let mesh = vec![
json!({"command": "mesh.hex.generate", "params": {"body": CRANK_HALF, "method": "extrude", "size": 3, "order": 2}}),
json!({"command": "mesh.mirror", "params": {"plane": "Sym", "bodies": [CRANK_HALF], "as": {CRANK_HALF: "CrankArm/b"}}}),
];
crank_model(bodies, mesh)
}
/// The crank arm's symmetry plane (`Sym`, y = 0) and the partition by it (`Half`): the one datum
/// the structured mesh needs.
fn crank_prepare() -> Value {
json!([
{"command": "geometry.datum", "params": {"name": "Sym", "by": {"type": "offset", "plane": "zx", "offset": 0}}},
{"command": "geometry.partition", "params": {"name": "Half", "datum": "Sym"}},
])
}
/// The crank's model after the `mesh` commands: material, the spindle fixed, the rider on the
/// pedal, step `Pedal`.
fn crank_model(bodies: &[Shape], mesh: Vec<Value>) -> Value {
let [spindle, pedal] = crank_faces(bodies);
let mut script = vec![json!({"command": "model.units", "params": {"system": "mm-t-s-N-MPa"}})];
script.extend(mesh);
script.extend(json_array(json!([
{"command": "model.set.create", "params": {"name": "crank", "geometry": bodies.iter().map(|b| json!({"body": b.name})).collect::<Vec<_>>()}},
{"command": "model.set.create", "params": {"name": "spindle", "geometry": spindle}},
{"command": "model.set.create", "params": {"name": "pedal", "geometry": pedal}},
{"command": "model.material.create", "params": {"name": "Al6061-T6", "elastic": {"type": "isotropic", "young": 68900, "poisson": 0.33}, "density": 2.7e-9}},
{"command": "model.section.create", "params": {"name": "Crank", "set": "crank", "material": "Al6061-T6", "kind": {"type": "solid"}}},
{"command": "model.boundary_condition.create", "params": {"name": "Spindle", "type": "fixed", "target": {"set": "spindle"}}},
{"command": "model.load.create", "params": {"name": "Rider", "type": "force", "target": {"set": "pedal"}, "vector": [0, -PEDAL_LOAD, 0]}},
{"command": "model.step.create", "params": {"name": "Pedal", "procedure": {"type": "static"}, "boundary_conditions": ["Spindle"], "loads": ["Rider"]}},
])));
Value::Array(script)
}
fn json_array(v: Value) -> Vec<Value> {
match v {
Value::Array(a) => a,
other => vec![other],
}
}
/// The crank's square-bore faces and pedal-hole faces as set members, found by their surfaces.
fn crank_faces(bodies: &[Shape]) -> [Vec<Value>; 2] {
use fieldcraft_geometry::FaceSurface;
let vertical = |axis: [f64; 3]| axis[2].abs() > 1.0 - 1e-6;
let (mut spindle, mut pedal) = (Vec::new(), Vec::new());
for body in bodies {
let surfaces = body.face_surfaces().unwrap_or_default();
for (face, surface) in body.faces().iter().zip(surfaces) {
let member = json!({"body": body.name, "face": face.name});
match surface {
Some(FaceSurface::Plane { normal, point })
if normal[2].abs() < 1e-6 && ((normal[0] * point[0] + normal[1] * point[1]).abs() - 6.35).abs() < 1e-6 =>
{
spindle.push(member)
}
Some(FaceSurface::Cylinder { origin, axis, radius })
if vertical(axis) && (radius - 1.5).abs() < 1e-6 && origin[0].hypot(origin[1]) < 8.0 =>
{
spindle.push(member)
}
Some(FaceSurface::Cylinder { origin, axis, radius })
if vertical(axis) && (radius - 7.0).abs() < 1e-6 && (origin[0] - 170.0).hypot(origin[1]) < 1e-6 =>
{
pedal.push(member)
}
_ => {}
}
}
}
[spindle, pedal]
}
/// Six times the signed volume of the tetrahedron `p[0..4]` (positive when p3 lies on the side
/// p0 → p1 → p2 turns counter-clockwise around).
fn signed_volume(p: &[[f64; 3]]) -> f64 {
@@ -225,6 +602,17 @@ mod tests {
use super::*;
use crate::Session;
/// The `file.sample` form offers every sample, by name.
#[test]
fn the_form_lists_every_sample() {
let Some(crate::schema::Kind::Choice(options)) = crate::cmd::forms::SAMPLE.first().map(|f| f.kind) else { panic!("not a choice") };
let mut offered: Vec<&str> = options.iter().map(|(n, _)| *n).collect();
let mut names: Vec<&str> = SAMPLES.iter().map(|s| s.name).collect();
offered.sort_unstable();
names.sort_unstable();
assert_eq!(offered, names);
}
#[test]
fn the_sample_builds_positive_elements_that_fill_both_parts() {
let mut s = Session::default();
@@ -266,4 +654,276 @@ mod tests {
assert_eq!((r["completed"].as_bool(), r["frames"].as_u64()), (Some(true), Some(11)), "{r}");
assert!(r["energy_balance"].as_f64().unwrap() < 0.05, "{r}");
}
/// `file.sample NAME`, checked clean: ready, no errors or warnings.
fn open(name: &str) -> Session {
let mut s = Session::default();
s.execute("file.sample", &json!({"name": name})).unwrap();
let check = s.execute("model.check", &json!({})).unwrap();
assert_eq!((check["ready"].as_bool(), check["errors"].as_u64(), check["warnings"].as_u64()), (Some(true), Some(0), Some(0)), "{check}");
s
}
/// The squeeze force of the ring, against the closed form for an incompressible Mooney–Rivlin
/// solid in uniaxial compression, P = 2 (λ − λ⁻²)(C10 + C01/λ) per unit of original area: the
/// same ring between frictionless plates (each face held only along z, the rigid motions
/// held at three nodes on the symmetry planes) compresses evenly and matches it within 3 %
/// (ν = 0.49 is nearly incompressible); bonded, the bulge needs more force (shape factor
/// ¼ (b − a)/h = 0.5 by the loaded over the free area), within 2.5 times.
#[test]
fn the_rubber_seal_squeezes_as_mooney_rivlin_rubber() {
let [inner, outer, height] = SEAL;
let area = std::f64::consts::PI * (outer * outer - inner * inner);
let lambda: f64 = 1.0 - SEAL_SQUEEZE / height;
let (c01, c10) = (0.2, 6.0 / (2.0 * 1.49) / 2.0 - 0.2);
let closed = 2.0 * (lambda - lambda.powi(-2)) * (c10 + c01 / lambda) * area;
let squeeze = |s: &mut Session| -> f64 {
s.execute("solve.nonlinear", &json!({})).unwrap();
let r = s.execute("results.reactions", &json!({"step": "Squeeze", "sets": ["top"]})).unwrap();
r["sets"][0]["force"][2].as_f64().unwrap()
};
let mut s = open("rubber-seal");
let bonded = squeeze(&mut s);
let node = |s: &Session, xyz: [f64; 3]| -> u32 {
*s.model.nodes().iter().find(|(_, n)| (0..3).all(|k| (n.xyz[k] - xyz[k]).abs() < 1e-9)).unwrap().0
};
let held = [
("hold_y", [inner, 0.0, 0.0], [None, Some(0.0), None]),
("hold_x", [0.0, inner, 0.0], [Some(0.0), None, None]),
("hold_y2", [-inner, 0.0, 0.0], [None, Some(0.0), None]),
];
for (name, at, [ux, uy, _]) in held {
let n = node(&s, at);
s.execute("model.set.create", &json!({"name": name, "nodes": [n]})).unwrap();
s.execute(
"model.boundary_condition.create",
&json!({"name": name, "type": "displacement", "target": {"set": name}, "values": [ux, uy, null, null, null, null]}),
)
.unwrap();
}
s.execute(
"model.boundary_condition.edit",
&json!({"name": "Base", "type": "displacement", "target": {"set": "bottom"}, "values": [null, null, 0, null, null, null]}),
)
.unwrap();
s.execute(
"model.boundary_condition.edit",
&json!({"name": "Press", "type": "displacement", "target": {"set": "top"}, "values": [null, null, -SEAL_SQUEEZE, null, null, null]}),
)
.unwrap();
s.execute("model.step.edit", &json!({"name": "Squeeze", "boundary_conditions": ["Base", "Press", "hold_y", "hold_x", "hold_y2"]})).unwrap();
let free = squeeze(&mut s);
assert!((free - closed).abs() < 0.03 * closed.abs(), "frictionless {free} N against {closed} N");
let stiffer = bonded / free;
assert!(stiffer > 1.05 && stiffer < 2.5, "bonded {bonded} N, frictionless {free} N");
}
#[test]
fn the_flow_sample_opens_ready_to_solve() {
let s = open("flow-past");
assert_eq!(s.model.fluid_domains().len(), 1);
}
/// The drag on the bracket, as a coefficient on the upright's frontal area (40 × 50 mm), is
/// that of a bluff plate standing on a wall at a Reynolds number of 83, raised by the 17 %
/// blockage of the box: between 1 and 3.5 (a flat plate broadside to the flow is about 1.2 at
/// high Reynolds number and rises as it falls). The lattice conserves mass.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_flow_past_the_bracket_has_a_bluff_body_drag() {
let mut s = open("flow-past");
let r = s.execute("solve.run", &json!({})).unwrap();
let r = &r["steps"][0]["summary"];
let drag: f64 = r["forces"].as_array().unwrap().iter().filter(|f| f["body"] == "Bracket").map(|f| f["mean"][0].as_f64().unwrap()).sum();
let [density, _] = AIR;
let cd = drag / (0.5 * density * FLOW_SPEED * FLOW_SPEED * 40.0 * 50.0);
assert!(cd > 1.0 && cd < 3.5, "Cd {cd}: {r}");
assert!(r["mass"]["relative_change"].as_f64().unwrap().abs() < 0.01, "{r}");
}
/// The heated bracket's 4 mm tet mesh stays near its 23 000 elements. #303: refinement piled
/// face vertices against a feature curve, and the improvement then grew the mesh to 29 257
/// elements in about two minutes. The element count is the check: wall time depends on the
/// machine and the build profile (about 5 s in a release build, far longer on CI).
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_heated_bracket_opens_with_its_usual_mesh() {
let s = open("heated-bracket");
let elements = s.model.elements().len();
assert!((20_000..=26_000).contains(&elements), "{elements} elements");
}
/// The heated bracket's temperatures lie between the air's and the heater's, falling along
/// the bracket away from the heater. Its thermal expansion: with the air at the heater's
/// temperature the bracket warms evenly by ΔT, and held at the foot's hole alone (at x = 40)
/// it grows freely, so a point moves α ΔT times its distance from the hole's axis along x:
/// the upright's top by −0.0432 mm (within 3 %), the foot's end by +0.024 mm (within 6 %).
/// The clamped bore cannot grow, which holds both points back a little; how much depends on
/// the tet mesh, which differs between platforms (#115): 2.1 % at the top on the Linux CI.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_heated_bracket_warms_and_expands_as_steel() {
let mut s = open("heated-bracket");
let r = s.execute("solve.run", &json!({})).unwrap();
let r = &r["steps"][0]["summary"];
assert!((r["max_temperature"]["value"].as_f64().unwrap() - HEATER).abs() < 1e-9, "{r}");
let probe = |s: &mut Session| s.execute("solve.probe", &json!({"step": "Heat", "at": [[4.0, 50.0, 20.0], [60.0, 4.0, 20.0]]})).unwrap();
let p = probe(&mut s);
let (upright, foot) = (p["nodes"][0]["temperature"].as_f64().unwrap(), p["nodes"][1]["temperature"].as_f64().unwrap());
assert!(upright > foot && foot > AMBIENT && upright <= HEATER, "{upright} {foot}");
let foot_hole = json!([{"body": "Bracket", "face": "F4:bore:side:0"}, {"body": "Bracket", "face": "F4:bore:side:1"}]);
s.execute("model.set.create", &json!({"name": "foot_hole", "geometry": foot_hole})).unwrap();
s.execute("model.boundary_condition.edit", &json!({"name": "Clamp", "type": "fixed", "target": {"set": "foot_hole"}})).unwrap();
s.execute("model.load.edit", &json!({"name": "Air", "type": "convection", "set": "skin", "film": 0.01, "sink": HEATER})).unwrap();
s.execute("solve.static", &json!({})).unwrap();
let p = probe(&mut s);
let grow = STEEL_EXPANSION * (HEATER - AMBIENT);
// The bore itself cannot grow, which holds back the foot's end, 16 mm from its edge, a
// little more than the upright's top, 32 mm away.
for (i, tolerance) in [(0, 0.03), (1, 0.06)] {
let node = &p["nodes"][i];
let (ux, expected) = (node["displacement"][0].as_f64().unwrap(), grow * (node["xyz"][0].as_f64().unwrap() - 40.0));
assert!((ux - expected).abs() < tolerance * expected.abs(), "{node}: {ux} against {expected}");
}
}
/// The hex20 bracket's tip deflection agrees with a fine tet10 solution of the unpartitioned
/// part (0.5093 mm, crates/testkit/tests/bracket_blocks.rs) within 1 %, its mesh conforms
/// across all 30 cells, and the load reaches the clamp.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_hex_bracket_bends_like_the_fine_tet_solution() {
let mut s = open("bracket-hex");
let elements = s.model.elements().values().filter(|e| e.kind == fieldcraft_model::ElementKind::Hex20).count();
assert_eq!(elements, s.model.elements().len());
let r = s.execute("solve.run", &json!({})).unwrap();
let r = &r["steps"][0]["summary"];
let probe = s.execute("solve.probe", &json!({"step": "Load", "at": [[60.0, 4.0, 20.0]]})).unwrap();
let tip = probe["nodes"][0]["displacement"][1].as_f64().unwrap();
assert!((tip + 0.5093).abs() < 0.01 * 0.5093, "{tip}");
let reaction = s.execute("results.reactions", &json!({"step": "Load", "sets": ["top"]})).unwrap();
assert!((reaction["sets"][0]["force"][1].as_f64().unwrap() - 1000.0).abs() < 1e-6, "{reaction}");
assert!(r["max_von_mises"]["value"].as_f64().unwrap() > 200.0, "{r}");
}
/// The crank opens as one conforming structured hex20 mesh: the half meshed in blocks
/// without partitions or seeds, no ties, the half and its mirror
/// image alike and joined on the symmetry plane, the spindle and pedal faces found on both
/// halves (the image's faces carry the names of the half they are the image of), and the
/// quality floor: scaled Jacobian at least 0.37, edge ratio at most 10.
#[test]
fn the_crank_opens_as_one_structured_mesh_of_two_alike_halves() {
let (arm, mirror) = (find("crank-arm").unwrap(), find("crank-mirror").unwrap());
let prepared = |x: &Sample| x.prepare.map(|f| f());
assert!(
arm.design == mirror.design && prepared(arm) == prepared(mirror) && (arm.script)(&[]) == (mirror.script)(&[]),
"one model under two names"
);
{
let name = "crank-arm";
let mut s = open(name);
let bodies: Vec<String> = s.design.as_ref().unwrap().bodies.iter().map(|b| b.name.clone()).collect();
assert_eq!(bodies, [CRANK_HALF, "CrankArm/b"]);
// One datum, the symmetry plane, hidden.
assert!(s.model.datums().len() == 1 && s.model.datums().keys().all(|d| !s.shows(crate::ItemKind::Datum, d)), "datums shown");
assert!(!s.is_dirty(), "a sample just opened has nothing to save");
assert!(s.model.ties().is_empty(), "no ties");
let elements = s.model.elements().values().filter(|e| e.kind == fieldcraft_model::ElementKind::Hex20).count();
assert_eq!(elements, s.model.elements().len());
let mut set = |name: &str, bodies: &[&str]| {
s.execute("model.set.create", &json!({"name": name, "geometry": bodies.iter().map(|b| json!({"body": b})).collect::<Vec<_>>()}))
.unwrap();
s.model.resolve_set(name).unwrap()
};
let (a, b) = (set("half_a", &[CRANK_HALF]), set("half_b", &["CrankArm/b"]));
assert_eq!(a.elements.len(), b.elements.len());
assert_eq!(a.elements.len() + b.elements.len(), elements);
assert_eq!(a.faces.len(), b.faces.len(), "the halves' skins are alike");
let shared = a.nodes.iter().filter(|n| b.nodes.binary_search(n).is_ok()).count();
assert!(shared > 100, "{shared}");
assert_eq!(a.nodes.len() + b.nodes.len() - shared, s.model.nodes().len());
let q = s.execute("mesh.quality", &json!({})).unwrap();
assert_eq!(q["valid"].as_u64().unwrap() as usize, elements, "{q}");
let metric = |m: &str, k: &str| q["metrics"][m][k].as_f64().unwrap();
assert!(metric("scaled_jacobian", "min") >= 0.37, "{q}");
assert!(metric("edge_ratio", "max") <= 10.0, "{q}");
let members = |set: &str| s.model.sets().get(set).map_or(Vec::new(), |x| x.geometry.iter().map(|g| g.body.clone()).collect::<Vec<_>>());
for set in ["spindle", "pedal"] {
let bodies = members(set);
assert!(bodies.iter().any(|b| b == CRANK_HALF) && bodies.iter().any(|b| b == "CrankArm/b"), "{set}: {bodies:?}");
assert!(!s.model.resolve_set(set).unwrap().faces.is_empty(), "{set}");
}
let faces = |set: &str| s.model.sets().get(set).map_or(0, |x| x.geometry.len());
assert_eq!((faces("spindle"), faces("pedal")), (10, 4), "{name}");
}
}
/// Solved, the crank's root bends as a beam: σxx on the arm's sides at x = 29 mm (35.6 mm
/// wide, 16 thick, 141 mm from the pedal) within 3 % of M/Z = 1500 · 141 / (16 · 35.6² / 6) =
/// 62.6 MPa, equal and opposite on the two mirror-image sides, and the spindle carries the
/// whole load.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_crank_arm_root_bends_as_the_beam_formula_says() {
let mut s = open("crank-arm");
s.execute("solve.run", &json!({})).unwrap();
let half_width: f64 = 19.0 - 7.0 * 29.0 / 170.0;
let probe = s.execute("solve.probe", &json!({"step": "Pedal", "at": [[29.0, -half_width, 8.0], [29.0, half_width, 8.0]]})).unwrap();
let sxx = |i: usize| probe["nodes"][i]["stress"][0].as_f64().unwrap();
let hand = PEDAL_LOAD * (170.0 - 29.0) / (16.0 * (2.0 * half_width).powi(2) / 6.0);
for (i, sign) in [(0, -1.0), (1, 1.0)] {
assert!((sign * sxx(i) - hand).abs() < 0.03 * hand, "{} against {hand} MPa: {probe}", sxx(i));
}
assert!((sxx(0) + sxx(1)).abs() < 0.01 * hand, "{probe}");
let reaction = s.execute("results.reactions", &json!({"step": "Pedal", "sets": ["spindle"]})).unwrap();
assert!((reaction["sets"][0]["force"][1].as_f64().unwrap() - PEDAL_LOAD).abs() < 1e-6, "{reaction}");
}
/// The conformity of `s`'s mesh ([`fieldcraft_mesh::quality::conformity`]).
fn conformity(s: &Session) -> fieldcraft_mesh::quality::Conformity {
let nodes: Vec<(u32, [f64; 3])> = s.model.nodes().iter().map(|(l, n)| (*l, n.xyz)).collect();
let elements = s.model.elements().iter().map(|(l, e)| (*l, e.kind, e.nodes.as_slice()));
fieldcraft_mesh::quality::conformity(&nodes, elements, 1e-6).unwrap()
}
/// The crank arm's hex20 mesh has no crack (#260): its free faces close up across the cells
/// and the mirror plane, no two nodes coincide and every element edge has one mid-side node.
#[test]
fn the_crank_arm_hex20_mesh_is_conforming() {
let s = open("crank-arm");
let c = conformity(&s);
assert!(c.is_conforming(), "{:?} {:?} {:?}", c.open_edges.first(), c.coincident.first(), c.midside_mismatches.first());
}
#[test]
fn the_drop_test_opens_ready_to_solve() {
let s = open("drop-test");
assert!(s.model.elements().len() > 1000);
}
/// The bracket's mass is ρ V (V: foot, upright and the fillet's corner, 36 − 9π mm² by 40 mm),
/// it meets the floor at √(2 g h) with ½ m v² of kinetic energy and conserves energy; by the
/// end the floor has taken half its downward momentum and turned kinetic energy into
/// vibration.
#[test]
#[ignore = "heavy: cargo xtask test --heavy (CI heavy job)"]
fn the_drop_test_lands_at_the_free_fall_speed_and_bounces() {
let mut s = open("drop-test");
let r = s.execute("solve.run", &json!({})).unwrap();
let r = &r["steps"][0]["summary"];
let volume = 60.0 * 8.0 * 40.0 + 8.0 * 42.0 * 40.0 + (36.0 - 9.0 * std::f64::consts::PI) * 40.0;
let mass = 2.7e-9 * volume;
let close = |a: f64, b: f64, rel: f64| (a - b).abs() <= rel * b.abs();
assert!(close(r["total_mass"].as_f64().unwrap(), mass, 0.005), "{r}");
assert!(r["completed"].as_bool() == Some(true) && r["energy_balance"].as_f64().unwrap() < 0.01, "{r}");
let h = s.execute("solve.history", &json!({"step": "Drop"})).unwrap();
let speed = (2.0 * GRAVITY * DROP_HEIGHT).sqrt();
let pz = |i: usize| h["momentum"][i][2].as_f64().unwrap();
let kinetic = |i: usize| h["energies"][i]["kinetic"].as_f64().unwrap();
assert!(close(pz(0), -mass * speed, 0.005), "{}", pz(0));
assert!(close(kinetic(0), 0.5 * mass * speed * speed, 0.01), "{}", kinetic(0));
let last = h["time"].as_array().unwrap().len() - 1;
let kept = pz(last) / pz(0);
assert!(kept > 0.4 && kept < 0.6 && kinetic(last) < kinetic(0), "{} {}", pz(last), kinetic(last));
}
}
+411 -35
View File
@@ -33,6 +33,12 @@ pub struct Field {
pub default: Option<&'static str>,
/// What an empty field means ("every body", "1/25 of the diagonal"), or a short note.
pub hint: &'static str,
/// What the field means, in a sentence or two, with a typical value: the form's tooltip and
/// the JSON Schema description. The unit is added from the field's dimension ([`Field::help_text`]).
pub help: &'static str,
/// For a [`Kind::Choice`]: a one-line note per option value (what it needs), shown under the
/// field for the option chosen.
pub notes: &'static [(&'static str, &'static str)],
}
/// What a field holds.
@@ -107,6 +113,7 @@ pub enum Collection {
ReferencePoint,
Coupling,
Contact,
Tie,
Mass,
Spring,
BoundaryCondition,
@@ -117,6 +124,15 @@ pub enum Collection {
SolvedStep,
/// A body of the open design.
Body,
/// A datum plane, axis or point.
Datum,
/// A datum plane.
DatumPlane,
/// A datum axis.
DatumAxis,
/// A datum point.
DatumPoint,
Partition,
}
impl Collection {
@@ -128,6 +144,7 @@ impl Collection {
Collection::ReferencePoint => "reference point",
Collection::Coupling => "coupling",
Collection::Contact => "contact",
Collection::Tie => "tie",
Collection::Mass => "point mass",
Collection::Spring => "spring",
Collection::BoundaryCondition => "boundary condition",
@@ -136,6 +153,11 @@ impl Collection {
Collection::Step => "step",
Collection::SolvedStep => "solved step",
Collection::Body => "body",
Collection::Datum => "datum",
Collection::DatumPlane => "datum plane",
Collection::DatumAxis => "datum axis",
Collection::DatumPoint => "datum point",
Collection::Partition => "partition",
}
}
}
@@ -151,6 +173,7 @@ impl Session {
Collection::ReferencePoint => Box::new(m.reference_points().keys().map(String::as_str)),
Collection::Coupling => Box::new(m.couplings().keys().map(String::as_str)),
Collection::Contact => Box::new(m.contacts().keys().map(String::as_str)),
Collection::Tie => Box::new(m.ties().keys().map(String::as_str)),
Collection::Mass => Box::new(m.masses().keys().map(String::as_str)),
Collection::Spring => Box::new(m.springs().keys().map(String::as_str)),
Collection::BoundaryCondition => Box::new(m.boundary_conditions().keys().map(String::as_str)),
@@ -159,6 +182,11 @@ impl Session {
Collection::Step => Box::new(m.steps().iter().map(|s| s.name.as_str())),
Collection::SolvedStep => Box::new(self.solved_steps()),
Collection::Body => Box::new(self.design.iter().flat_map(|d| d.bodies.iter().map(|b| b.name.as_str()))),
Collection::Datum => Box::new(m.datums().keys().map(String::as_str)),
Collection::DatumPlane => Box::new(m.datums().iter().filter(|(_, d)| d.plane().is_some()).map(|(n, _)| n.as_str())),
Collection::DatumAxis => Box::new(m.datums().iter().filter(|(_, d)| d.axis().is_some()).map(|(n, _)| n.as_str())),
Collection::DatumPoint => Box::new(m.datums().iter().filter(|(_, d)| d.point().is_some()).map(|(n, _)| n.as_str())),
Collection::Partition => Box::new(m.partitions().iter().map(|p| p.name.as_str())),
};
names.take(MAX_NAMES).map(str::to_string).collect()
}
@@ -199,6 +227,43 @@ pub enum Dim {
}
impl Dim {
/// The dimension's name ("stress", "length"); `None` for [`Dim::None`].
pub fn name(self) -> Option<&'static str> {
Some(match self {
Dim::None => return None,
Dim::Length | Dim::Millimetre => "length",
Dim::Area => "area",
Dim::Stress => "stress",
Dim::Density => "density",
Dim::Force => "force",
Dim::Moment => "moment",
Dim::Mass => "mass",
Dim::Inertia => "rotary inertia",
Dim::Time => "time",
Dim::Velocity => "velocity",
Dim::Acceleration => "acceleration",
Dim::AngularVelocity => "angular velocity",
Dim::Stiffness => "stiffness",
Dim::Damping => "damping",
Dim::Viscosity => "viscosity",
Dim::ForcePerVolume => "force per volume",
Dim::Power => "power",
Dim::HeatFlux => "heat flux",
Dim::FilmCoefficient => "film coefficient",
Dim::Conductivity => "conductivity",
Dim::SpecificHeat => "specific heat",
Dim::Expansion => "expansion",
Dim::Temperature => "temperature",
Dim::Degree => "angle",
Dim::Hertz => "frequency",
})
}
/// Whether its unit follows the model's unit system (a fixed unit such as degrees does not).
pub fn follows_system(self) -> bool {
self.name().is_some() && self.unit(UnitSystem::Unspecified).is_none()
}
/// Its unit in `system`, or `None` (no unit, or the system is unspecified).
pub fn unit(self, system: UnitSystem) -> Option<String> {
let fixed = match self {
@@ -252,7 +317,7 @@ impl Dim {
// ---- Building fields (const, so schemas are static tables) ----
const fn field(key: &'static str, label: &'static str, kind: Kind) -> Field {
Field { key, label, kind, required: false, default: None, hint: "" }
Field { key, label, kind, required: false, default: None, hint: "", help: "", notes: &[] }
}
impl Field {
@@ -268,8 +333,62 @@ impl Field {
pub const fn hint(self, hint: &'static str) -> Field {
Field { hint, ..self }
}
/// What it means ([`Field::help`]).
pub const fn help(self, help: &'static str) -> Field {
Field { help, ..self }
}
/// A one-line note per option value ([`Field::notes`]).
pub const fn notes(self, notes: &'static [(&'static str, &'static str)]) -> Field {
Field { notes, ..self }
}
/// The note for this option value (the default when `None`).
pub fn note(&self, value: Option<&str>) -> Option<&'static str> {
let value = value.or_else(|| self.default.map(|d| d.trim_matches('"')))?;
self.notes.iter().find(|(v, _)| *v == value).map(|(_, n)| *n)
}
/// Its physical dimension, for a number or a vector of numbers.
pub fn dim(&self) -> Option<Dim> {
match self.kind {
Kind::Number { dim, .. } | Kind::Vector { dim, .. } => Some(dim),
_ => None,
}
}
/// What its value is measured in, as a form shows it: the unit in `system` ("MPa"), or, with
/// no unit system, the dimension in brackets ("[stress]"). `None` for a number without a unit.
pub fn unit_label(&self, system: UnitSystem) -> Option<String> {
let dim = self.dim()?;
dim.unit(system).or_else(|| dim.name().map(|n| format!("[{n}]")))
}
/// The help as the form's tooltip shows it: [`Field::help`] and the unit (or, with no unit system, the dimension and where to set the system).
pub fn help_text(&self, system: UnitSystem) -> String {
let mut out = self.help.to_string();
let mut line = |s: String| {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&s);
};
if let Some(dim) = self.dim() {
match (dim.unit(system), dim.name()) {
(Some(u), _) => line(format!("Unit: {u}.")),
(None, Some(n)) => {
let hint = if system == UnitSystem::Unspecified { format!(" {UNITS_HINT}") } else { String::new() };
line(format!("Unit: a {n} in the model's units.{hint}"))
}
(None, None) => {}
}
}
out
}
}
/// What a form says when the model has no unit system.
pub const UNITS_HINT: &str = "Set a unit system: Properties › Units.";
pub const fn num(key: &'static str, label: &'static str, dim: Dim) -> Field {
field(key, label, Kind::Number { dim, min: None, max: None })
}
@@ -333,7 +452,7 @@ pub const fn variant(tag: &'static str, label: &'static str, fields: &'static [F
}
/// The `name` of a new or edited definition.
pub const NAME: Field = text("name", "Name").req();
pub const NAME: Field = text("name", "Name").req().help("A name for it, unique among its kind; other definitions refer to it by this name.");
impl Kind {
/// The variant of `tag`, for [`Kind::Variants`].
@@ -436,26 +555,223 @@ pub fn switch_variant(f: &Field, common: &[Field], old: &Map<String, Value>, tag
out
}
/// A problem with a field's value, for the form to show beside it.
#[derive(Debug, Clone, PartialEq)]
/// A problem with a field's value: the field, where it is, and what is wrong. [`Problem::for_form`]
/// phrases it by the field's label (the form), [`Problem::for_agents`] by its JSON path (agents,
/// the engine's messages).
#[derive(Debug, Clone)]
pub struct Problem {
/// The JSON path of the field (`elastic/young`).
/// The JSON path of the field (`elastic/young`, `rows/0/name`); empty for the parameters as a
/// whole.
pub path: String,
pub message: String,
/// The field it is about; `None` for the parameters as a whole. For a variant's tag, the
/// [`Kind::Variants`] field.
pub field: Option<&'static Field>,
pub kind: ProblemKind,
}
/// What is wrong with a value.
#[derive(Debug, Clone, PartialEq)]
pub enum ProblemKind {
/// Left out (or empty text).
Required,
/// Not a finite number.
NotANumber,
/// A number below the field's minimum.
Below(f64),
/// A number above the field's maximum.
Above(f64),
/// Not a whole number in `min..=max`.
NotAWholeNumber {
min: i64,
max: i64,
},
NotText,
NotABool,
/// Not one of the field's choices (or, for [`Kind::Either`], of its options).
NotAChoice,
/// Not a list of `len` numbers.
NotAVector {
len: usize,
},
NotNames,
NotAnObject,
/// A variant tag the field does not have (`None`: no tag at all).
UnknownVariant(Option<String>),
/// More rows than `max`, or not a list.
TooManyRows {
max: usize,
},
/// Not a number greater than 0.
NotPositive,
/// Not a number in `min..=max`.
NotInRange {
min: f64,
max: f64,
},
/// Not a list of at most `max` of `what` ("[x, y, z]", "labels").
NotAList {
max: usize,
what: &'static str,
},
NotAName,
NotAPath,
/// Wrong for a reason the schema does not describe: what it must be or do instead
/// ("names the region of 2D elements; a solid block fills its body").
Invalid(String),
}
impl PartialEq for Problem {
/// Problems are equal when they are about the same path and are the same problem (the field
/// is where the path leads).
fn eq(&self, other: &Self) -> bool {
self.path == other.path && self.kind == other.kind
}
}
impl Problem {
fn new(path: String, field: &'static Field, kind: ProblemKind) -> Self {
Problem { path, field: Some(field), kind }
}
/// A problem with the value at `path`, its field not looked up yet ([`Problem::in_form`]).
pub fn at(path: impl Into<String>, kind: ProblemKind) -> Self {
Problem { path: path.into(), field: None, kind }
}
/// The problem with its field looked up in `fields` (when it has none yet and the path is
/// there).
pub fn in_form(mut self, fields: &'static [Field]) -> Self {
if self.field.is_none() && !self.path.is_empty() {
self.field = field_at(fields, &self.path);
}
self
}
/// What the value must be, without the field's name ("required", "at least 0").
pub fn expected(&self) -> String {
let f = self.field;
match &self.kind {
ProblemKind::Required => "required".into(),
ProblemKind::NotANumber => "a number".into(),
ProblemKind::Below(lo) => format!("at least {lo}"),
ProblemKind::Above(hi) => format!("at most {hi}"),
ProblemKind::NotAWholeNumber { min, max } => format!("a whole number in {min}..={max}"),
ProblemKind::NotText => "text".into(),
ProblemKind::NotABool => "true or false".into(),
ProblemKind::NotAChoice => match f.map(|f| f.kind) {
Some(Kind::Choice(options)) => format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", ")),
Some(Kind::Either(options)) => format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")),
_ => "one of the choices".into(),
},
ProblemKind::NotAVector { len } => format!("{len} numbers"),
ProblemKind::NotNames => "a list of names".into(),
ProblemKind::NotAnObject if f.is_none() => "a JSON object".into(),
ProblemKind::NotAnObject => "an object".into(),
ProblemKind::UnknownVariant(Some(t)) => format!("a known {} (not `{t}`)", f.map_or("type".into(), |f| f.label.to_lowercase())),
ProblemKind::UnknownVariant(None) => match f.map(|f| f.kind) {
Some(Kind::Variants { tag, .. }) => format!("an object with a known `{tag}`"),
_ => "an object with a known type".into(),
},
ProblemKind::TooManyRows { max } => format!("a list of at most {max} rows"),
ProblemKind::NotPositive => "a positive number".into(),
ProblemKind::NotInRange { min, max } => format!("a number in {min}..={max}"),
ProblemKind::NotAList { max, what } => format!("a list of at most {max} {what}"),
ProblemKind::NotAName => "a name".into(),
ProblemKind::NotAPath => "a file path".into(),
ProblemKind::Invalid(why) => why.clone(),
}
}
/// The problem as agents read it, naming the field by its JSON path:
/// "`elastic/young` is required", "`bands` must be a whole number in 2..=24".
pub fn for_agents(&self) -> String {
self.phrase(Naming::Key)
}
/// The problem as a form shows it, naming the field by its label and saying what to do:
/// "Material: choose a material", "Young's modulus: must be at least 0".
pub fn for_form(&self) -> String {
self.phrase(Naming::Label)
}
/// The one phrasing of a problem, naming the field by its key or by its label.
pub fn phrase(&self, naming: Naming) -> String {
let by_label = naming == Naming::Label;
let field = self.field.filter(|_| by_label);
let subject = match field {
Some(f) => format!("{}:", f.label),
None if self.path.is_empty() => if by_label { "The parameters" } else { "the parameters" }.to_string(),
None => format!("`{}`", self.path),
};
let required = self.kind == ProblemKind::Required;
let what = match (field.map(|f| f.kind), &self.kind) {
(_, ProblemKind::Invalid(why)) => why.clone(),
(None, _) if required => "is required".into(),
(None, _) => format!("must be {}", self.expected()),
(Some(Kind::Ref(c)), _) if required => format!("choose {}", article(c.label())),
(Some(Kind::RefList(c)), _) if required => format!("choose at least one {}", c.label()),
(Some(Kind::Either(options)), _) => {
format!("choose {}", options.iter().map(|o| article(&lower(o.label))).collect::<Vec<_>>().join(" or "))
}
(Some(Kind::Choice(options)), _) => format!("choose one of {}", options.iter().map(|(_, l)| *l).collect::<Vec<_>>().join(", ")),
(Some(Kind::Variants { .. }), _) => format!("choose {}", article(&lower(field.map_or("", |f| f.label)))),
(Some(Kind::Path { .. }), _) if required => "enter a path".into(),
(Some(Kind::Text), _) if required && field.is_some_and(|f| f.key == "name") => "enter a name".into(),
(Some(_), _) if required => "required".into(),
(Some(_), _) => format!("must be {}", self.expected()),
};
format!("{subject} {what}")
}
}
/// How a problem names its field: by its JSON path (agents) or by its label (a form).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Naming {
Key,
Label,
}
/// A command's problem with `params`, made as precise as its form `fields` can: when the
/// command names a group (`plastic`) and the form finds a problem with a field inside it
/// (`plastic/yield_stress` left out), that problem; otherwise the command's own, with its field
/// looked up.
pub fn refine(fields: &'static [Field], params: &Value, problem: Problem) -> Problem {
let inside = |p: &Problem| p.path.strip_prefix(problem.path.as_str()).is_some_and(|r| r.starts_with('/'));
if !problem.path.is_empty()
&& let Some(precise) = problems(fields, params).into_iter().find(inside)
{
return precise;
}
problem.in_form(fields)
}
/// "a material", "an element".
fn article(noun: &str) -> String {
let an = noun.starts_with(['a', 'e', 'i', 'o', 'u']);
format!("{} {noun}", if an { "an" } else { "a" })
}
/// A label lower-cased, but not its acronyms ("Reference point" → "reference point", "RBE2" stays).
fn lower(label: &str) -> String {
let mut chars = label.chars();
match (chars.next(), chars.next()) {
(Some(c), Some(d)) if d.is_lowercase() => c.to_lowercase().chain(label.chars().skip(1)).collect(),
_ => label.to_string(),
}
}
/// What is missing or out of range in `params`: required fields left out, numbers outside
/// their range, values of the wrong kind. An empty list does not promise the command accepts
/// them (it checks more); a problem means it would not.
pub fn problems(fields: &[Field], params: &Value) -> Vec<Problem> {
pub fn problems(fields: &'static [Field], params: &Value) -> Vec<Problem> {
match params.as_object() {
Some(obj) => object_problems(fields, obj),
None => vec![Problem { path: String::new(), message: "the parameters must be a JSON object".into() }],
None => vec![Problem { path: String::new(), field: None, kind: ProblemKind::NotAnObject }],
}
}
/// [`problems`] of an object's fields.
pub fn object_problems(fields: &[Field], obj: &Map<String, Value>) -> Vec<Problem> {
pub fn object_problems(fields: &'static [Field], obj: &Map<String, Value>) -> Vec<Problem> {
let mut out = Vec::new();
check(fields, obj, "", &mut out, 0);
out
@@ -472,7 +788,42 @@ pub fn join(prefix: &str, key: &str) -> String {
}
}
fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec<Problem>, depth: usize) {
/// The field at `path` (`elastic/young`, `rows/0/name`), for a key the engine names. A variant's
/// tag gives its [`Kind::Variants`] field; an [`Kind::Either`] option's key gives the option.
pub fn field_at(fields: &'static [Field], path: &str) -> Option<&'static Field> {
let mut segments = path.split('/');
let mut field = find(fields, segments.next()?)?;
for (depth, segment) in segments.enumerate() {
if depth > MAX_DEPTH {
return None;
}
field = match field.kind {
Kind::Rows { .. } if segment.parse::<usize>().is_ok() => field,
Kind::Group(inner) | Kind::Rows { fields: inner, .. } => find(inner, segment)?,
Kind::Variants { tag, .. } if tag == segment => field,
Kind::Variants { variants, .. } => variants.iter().find_map(|v| find(v.fields, segment))?,
Kind::Either(options) => options.iter().find(|o| o.key == segment)?,
_ => return None,
};
}
Some(field)
}
/// The field of `fields` with key `key`, looking into flattened variants.
fn find(fields: &'static [Field], key: &str) -> Option<&'static Field> {
fields.iter().find_map(|f| match f.kind {
Kind::Variants { tag, variants } if f.key.is_empty() => {
if tag == key {
Some(f)
} else {
variants.iter().find_map(|v| find(v.fields, key))
}
}
_ => (f.key == key).then_some(f),
})
}
fn check(fields: &'static [Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec<Problem>, depth: usize) {
if depth > MAX_DEPTH || out.len() > MAX_ROWS {
return;
}
@@ -483,20 +834,20 @@ fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec
match obj.get(tag).and_then(Value::as_str) {
Some(t) => match f.kind.variant(t) {
Some(v) => check(v.fields, obj, prefix, out, depth + 1),
None => out.push(Problem { path: join(prefix, tag), message: format!("`{t}` is not a {}", f.label.to_lowercase()) }),
None => out.push(Problem::new(join(prefix, tag), f, ProblemKind::UnknownVariant(Some(t.to_string())))),
},
None if f.required => out.push(Problem { path: join(prefix, tag), message: "required".into() }),
None if f.required => out.push(Problem::new(join(prefix, tag), f, ProblemKind::Required)),
None => {}
}
continue;
}
let path = join(prefix, f.key);
match obj.get(f.key) {
None | Some(Value::Null) if f.required => out.push(Problem { path, message: "required".into() }),
None | Some(Value::Null) if f.required => out.push(Problem::new(path, f, ProblemKind::Required)),
None | Some(Value::Null) => {}
Some(v) => {
if let Some(message) = value_problem(f, v, &path, out, depth) {
out.push(Problem { path, message });
if let Some(kind) = value_problem(f, v, &path, out, depth) {
out.push(Problem::new(path, f, kind));
}
}
}
@@ -504,39 +855,39 @@ fn check(fields: &[Field], obj: &Map<String, Value>, prefix: &str, out: &mut Vec
}
/// What is wrong with `v` as the value of `f`; nested problems go to `out`.
fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth: usize) -> Option<String> {
fn value_problem(f: &'static Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth: usize) -> Option<ProblemKind> {
match f.kind {
Kind::Number { min, max, .. } => match (v.as_f64().filter(|x| x.is_finite()), min, max) {
(None, ..) => Some("a number".into()),
(Some(x), Some(lo), _) if x < lo => Some(format!("at least {lo}")),
(Some(x), _, Some(hi)) if x > hi => Some(format!("at most {hi}")),
(None, ..) => Some(ProblemKind::NotANumber),
(Some(x), Some(lo), _) if x < lo => Some(ProblemKind::Below(lo)),
(Some(x), _, Some(hi)) if x > hi => Some(ProblemKind::Above(hi)),
_ => None,
},
Kind::Integer { min, max } => match v.as_i64() {
Some(x) if (min..=max).contains(&x) => None,
_ => Some(format!("a whole number in {min}..={max}")),
_ => Some(ProblemKind::NotAWholeNumber { min, max }),
},
Kind::Text | Kind::Path { .. } | Kind::Ref(_) => match v.as_str() {
Some(s) if f.required && s.trim().is_empty() => Some("required".into()),
Some(s) if f.required && s.trim().is_empty() => Some(ProblemKind::Required),
Some(_) => None,
None => Some("text".into()),
None => Some(ProblemKind::NotText),
},
Kind::Bool => (!v.is_boolean()).then(|| "true or false".into()),
Kind::Bool => (!v.is_boolean()).then_some(ProblemKind::NotABool),
Kind::Choice(options) => match v.as_str() {
Some(s) if options.iter().any(|(o, _)| *o == s) => None,
_ => Some(format!("one of {}", options.iter().map(|(o, _)| *o).collect::<Vec<_>>().join(", "))),
_ => Some(ProblemKind::NotAChoice),
},
Kind::Vector { labels, nullable, .. } => match v.as_array() {
Some(a) if a.len() == labels.len() && a.iter().all(|x| x.as_f64().is_some_and(f64::is_finite) || (nullable && x.is_null())) => None,
_ => Some(format!("{} numbers", labels.len())),
_ => Some(ProblemKind::NotAVector { len: labels.len() }),
},
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then(|| "a list of names".into()),
Kind::RefList(_) => (!v.as_array().is_some_and(|a| a.iter().all(Value::is_string))).then_some(ProblemKind::NotNames),
Kind::Group(fields) => match v.as_object() {
Some(o) => {
check(fields, o, path, out, depth + 1);
None
}
None => Some("an object".into()),
None => Some(ProblemKind::NotAnObject),
},
Kind::Variants { tag, .. } => match v.as_object() {
Some(o) => match o.get(tag).and_then(Value::as_str).and_then(|t| f.kind.variant(t)) {
@@ -544,9 +895,9 @@ fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth
check(var.fields, o, path, out, depth + 1);
None
}
None => Some(format!("needs a known `{tag}`")),
None => Some(ProblemKind::UnknownVariant(None)),
},
None => Some("an object".into()),
None => Some(ProblemKind::NotAnObject),
},
Kind::Either(options) => {
let ok = match v {
@@ -556,20 +907,21 @@ fn value_problem(f: &Field, v: &Value, path: &str, out: &mut Vec<Problem>, depth
}),
_ => false,
};
(!ok).then(|| format!("one of {}", options.iter().map(|o| o.key).collect::<Vec<_>>().join(", ")))
(!ok).then_some(ProblemKind::NotAChoice)
}
Kind::Unit | Kind::Json => None,
Kind::Rows { fields, max } => match v.as_array() {
Some(a) if a.len() <= max => {
for (i, row) in a.iter().enumerate() {
let row_path = format!("{path}/{i}");
match row.as_object() {
Some(o) => check(fields, o, &format!("{path}/{i}"), out, depth + 1),
None => out.push(Problem { path: format!("{path}/{i}"), message: "an object".into() }),
Some(o) => check(fields, o, &row_path, out, depth + 1),
None => out.push(Problem::new(row_path, f, ProblemKind::NotAnObject)),
}
}
None
}
_ => Some(format!("a list of at most {max} rows")),
_ => Some(ProblemKind::TooManyRows { max }),
},
}
}
@@ -662,8 +1014,14 @@ fn field_schema(f: &Field, depth: usize) -> Value {
_ => json!({}),
};
s["title"] = json!(f.label);
if !f.hint.is_empty() {
s["description"] = json!(f.hint);
let description = match (f.help, f.hint) {
("", "") => None,
(help, "") => Some(help.to_string()),
("", hint) => Some(hint.to_string()),
(help, hint) => Some(format!("{help} Empty or default: {hint}.")),
};
if let Some(d) = description {
s["description"] = json!(d);
}
if let Some(d) = parse_default(f) {
s["default"] = d;
@@ -723,6 +1081,24 @@ mod tests {
assert!(super::problems(LOADISH, &json!([1])).len() == 1);
}
/// One problem, two phrasings: by label for the form, by path for agents.
#[test]
fn problems_carry_their_field_and_kind() {
let p = problems(LOADISH, &json!({"type": "pressure", "magnitude": "x"}));
let kinds: Vec<(&str, &ProblemKind)> = p.iter().map(|p| (p.path.as_str(), &p.kind)).collect();
assert_eq!(kinds, [("name", &ProblemKind::Required), ("magnitude", &ProblemKind::NotANumber), ("set", &ProblemKind::Required)]);
assert_eq!(p.iter().map(Problem::for_form).collect::<Vec<_>>(), ["Name: enter a name", "Magnitude: must be a number", "Set: choose a set"]);
assert_eq!(
p.iter().map(Problem::for_agents).collect::<Vec<_>>(),
["`name` is required", "`magnitude` must be a number", "`set` is required"]
);
let unknown = problems(LOADISH, &json!({"name": "a", "type": "spin"}));
assert_eq!(unknown.first().map(Problem::for_form).as_deref(), Some("Type: choose a type"));
assert_eq!(unknown.first().map(Problem::for_agents).as_deref(), Some("`type` must be a known type (not `spin`)"));
assert_eq!(problems(LOADISH, &json!([1])).first().map(Problem::for_agents).as_deref(), Some("the parameters must be a JSON object"));
assert!(field_at(LOADISH, "magnitude").is_some_and(|f| f.label == "Magnitude"));
}
#[test]
fn json_schema_has_variants_and_requirements() {
let s = json_schema(LOADISH);
+593
View File
@@ -0,0 +1,593 @@
//! Anonymous usage analytics, off until the user agrees (docs/privacy.md).
//!
//! The app records [`Event`]s here; a host (the desktop app's sender thread, the web page's
//! `fetch`) takes them in batches ([`take_batch`]) and posts [`Batch::body`] to PostHog's batch
//! API. Nothing here touches the network.
//!
//! What an event can hold is fixed by its type: command ids, sample names and requirements come
//! from the registries (`&'static str`), never from parameters, paths, file names or messages.
//! Recording does nothing until [`enable`] (the user agreed, and the host may send); [`disable`]
//! drops what is queued. The queue is bounded ([`MAX_QUEUED`]): when full, new events are dropped.
//!
//! [`Session::execute`](crate::Session::execute) counts every top-level command of a session
//! whose [`Session::origin`](crate::Session::origin) is set (the app's own model): its id, kind,
//! duration, whether it failed and how, and where it came from ([`Origin`]); the funnel's
//! [`Milestone`]s and [`Event::SampleOpened`] follow from the same commands.
use std::cell::Cell;
use std::collections::VecDeque;
use std::sync::Mutex;
use serde_json::{Map, Value, json};
use crate::requirement::Requirement;
use crate::{CommandKind, EngineError};
/// PostHog Cloud's EU ingestion host.
pub const DEFAULT_HOST: &str = "https://eu.i.posthog.com";
/// Events kept waiting to be sent; more are dropped.
pub const MAX_QUEUED: usize = 1000;
/// Events in one request.
pub const MAX_BATCH: usize = 100;
/// Where a command came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin {
/// A click: the ribbon, a menu, a form, the browser.
Ui,
/// The command search or the command line.
Palette,
/// A script or the control channel.
Script,
/// An AI agent through the MCP server.
Mcp,
}
impl Origin {
pub fn as_str(self) -> &'static str {
match self {
Origin::Ui => "ui",
Origin::Palette => "palette",
Origin::Script => "script",
Origin::Mcp => "mcp",
}
}
/// Scripts and agents, which the user can leave out on their own.
pub fn automated(self) -> bool {
matches!(self, Origin::Script | Origin::Mcp)
}
}
/// A step of the way from a design to results, counted once per run.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Milestone {
DesignOpened,
Meshed,
Solved,
ResultsViewed,
}
impl Milestone {
pub fn as_str(self) -> &'static str {
match self {
Milestone::DesignOpened => "design_opened",
Milestone::Meshed => "meshed",
Milestone::Solved => "solved",
Milestone::ResultsViewed => "results_viewed",
}
}
fn bit(self) -> u8 {
1 << self as u8
}
}
/// Something that happened, with only what docs/privacy.md lists.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
AppStarted,
/// The window closed after `seconds`.
AppClosed {
seconds: u64,
},
CommandRun {
command: &'static str,
kind: CommandKind,
duration_ms: u64,
error: Option<&'static str>,
from: Origin,
},
Milestone(Milestone),
SampleOpened {
name: &'static str,
},
/// A command's form closed without running it.
FormCancelled {
command: &'static str,
},
/// A command clicked before the model had what it needs.
UnavailableClicked {
command: &'static str,
missing: Vec<Requirement>,
},
}
impl Event {
pub fn name(&self) -> &'static str {
match self {
Event::AppStarted => "app_started",
Event::AppClosed { .. } => "app_closed",
Event::CommandRun { .. } => "command_run",
Event::Milestone(_) => "milestone",
Event::SampleOpened { .. } => "sample_opened",
Event::FormCancelled { .. } => "form_cancelled",
Event::UnavailableClicked { .. } => "unavailable_clicked",
}
}
/// The event's own properties.
pub fn properties(&self) -> Map<String, Value> {
let v = match self {
Event::AppStarted => json!({}),
Event::AppClosed { seconds } => json!({"duration_s": seconds}),
Event::CommandRun { command, kind, duration_ms, error, from } => {
let kind = match kind {
CommandKind::Model => "model",
CommandKind::Session => "session",
};
let mut v = json!({"command": command, "kind": kind, "duration_ms": duration_ms, "ok": error.is_none(), "from": from.as_str()});
if let Some(e) = error {
v["error"] = json!(e);
}
v
}
Event::Milestone(m) => json!({"name": m.as_str()}),
Event::SampleOpened { name } => json!({"name": name}),
Event::FormCancelled { command } => json!({"command": command}),
Event::UnavailableClicked { command, missing } => json!({"command": command, "missing": missing}),
};
match v {
Value::Object(m) => m,
_ => Map::new(),
}
}
}
/// The class of an error, without its message (which can name the user's files and values).
pub fn error_class(e: &EngineError) -> &'static str {
match e {
EngineError::UnknownCommand(_) => "unknown_command",
EngineError::Params(_) | EngineError::Param(_) => "params",
EngineError::Model(_) => "model",
EngineError::Geometry(_) => "geometry",
EngineError::Mesh(_) => "mesh",
EngineError::File(_) => "file",
EngineError::Deck(_) => "deck",
EngineError::Solver(_) => "solver",
EngineError::Explicit(_) => "explicit",
EngineError::Fluid(_) => "fluid",
EngineError::Unavailable(_) => "unavailable",
EngineError::Internal { .. } => "internal",
}
}
/// Who is sending: the anonymous install and the build. The same for every event of a run.
#[derive(Clone, Debug, PartialEq)]
pub struct Identity {
/// A random id made for this install (not derived from the machine or the user).
pub install_id: String,
/// `desktop` or `web`.
pub platform: &'static str,
/// The operating system (`macos`, `linux`, `windows`; `web` in a browser).
pub os: &'static str,
pub arch: &'static str,
pub app_version: &'static str,
}
/// What [`take_batch`] hands the sender.
#[derive(Clone, Debug, PartialEq)]
pub struct Batch {
pub identity: Identity,
pub events: Vec<Event>,
}
impl Batch {
/// The body of a POST to PostHog's `/batch/` endpoint with the project's API key: each event
/// with the anonymous install id, the build, no person profile and no IP-based location.
pub fn body(&self, api_key: &str) -> String {
let id = &self.identity;
let batch: Vec<Value> = self
.events
.iter()
.map(|e| {
let mut p = e.properties();
p.insert("app_version".into(), json!(id.app_version));
p.insert("platform".into(), json!(id.platform));
p.insert("os".into(), json!(id.os));
p.insert("arch".into(), json!(id.arch));
p.insert("$process_person_profile".into(), json!(false));
p.insert("$geoip_disable".into(), json!(true));
json!({"event": e.name(), "distinct_id": id.install_id, "properties": p})
})
.collect();
json!({"api_key": api_key, "batch": batch}).to_string()
}
}
/// Whether this run may record at all, before asking the user: the build has a project key,
/// `FIELDCRAFT_TELEMETRY` (`telemetry`) is not `0`, and a run driven by automation (`--control`)
/// or CI records only when `FIELDCRAFT_TELEMETRY=1` says so.
pub fn allowed(has_key: bool, telemetry: Option<&str>, automation: bool, ci: bool) -> bool {
let set = telemetry.map(|v| v.trim().to_ascii_lowercase());
match set.as_deref() {
Some("0" | "false" | "off" | "no") => false,
Some("1" | "true" | "on" | "yes") => has_key,
_ => has_key && !automation && !ci,
}
}
struct State {
identity: Identity,
/// Count scripts and MCP runs too.
automation: bool,
queue: VecDeque<Event>,
/// Milestones already sent this run.
reached: u8,
/// When recording started ([`now_ms`]), for the session's length.
started: Option<f64>,
}
static STATE: Mutex<Option<State>> = Mutex::new(None);
fn with_state<R>(f: impl FnOnce(&mut Option<State>) -> R) -> R {
// A poisoned lock still holds a usable queue.
let mut g = STATE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
f(&mut g)
}
/// Start recording, as `identity`, with [`Event::AppStarted`]; `automation` counts scripts and
/// MCP runs too. Already recording, only the settings change.
pub fn enable(identity: Identity, automation: bool) {
let now = now_ms();
with_state(|s| match s {
Some(s) => {
s.identity = identity;
s.automation = automation;
}
None => *s = Some(State { identity, automation, queue: VecDeque::from([Event::AppStarted]), reached: 0, started: now }),
});
}
/// The app is closing: [`Event::AppClosed`] with how long it recorded.
pub fn closing() {
let now = now_ms();
let started = with_state(|s| s.as_ref().map(|s| s.started));
if let Some(started) = started {
let seconds = match (started, now) {
(Some(a), Some(b)) if b >= a => ((b - a) / 1000.0).round() as u64,
_ => 0,
};
record(Event::AppClosed { seconds });
}
}
/// Stop recording and drop everything queued.
pub fn disable() {
with_state(|s| *s = None);
}
pub fn enabled() -> bool {
with_state(|s| s.is_some())
}
/// Queue an event, when recording (and when it is no script or MCP run the user left out).
pub fn record(event: Event) {
with_state(|s| {
let Some(s) = s else { return };
match &event {
Event::CommandRun { from, .. } if from.automated() && !s.automation => return,
Event::Milestone(m) if s.reached & m.bit() != 0 => return,
Event::Milestone(m) => s.reached |= m.bit(),
_ => {}
}
if s.queue.len() < MAX_QUEUED {
s.queue.push_back(event);
}
});
}
/// Up to [`MAX_BATCH`] queued events to send, oldest first; `None` when there are none.
pub fn take_batch() -> Option<Batch> {
with_state(|s| {
let s = s.as_mut()?;
if s.queue.is_empty() {
return None;
}
let n = s.queue.len().min(MAX_BATCH);
Some(Batch { identity: s.identity.clone(), events: s.queue.drain(..n).collect() })
})
}
/// Events waiting to be sent.
pub fn queued() -> usize {
with_state(|s| s.as_ref().map_or(0, |s| s.queue.len()))
}
/// A clock in milliseconds for command durations. The plain wasm target has none: the web page
/// sets one ([`set_clock`]).
static CLOCK: Mutex<Option<fn() -> f64>> = Mutex::new(None);
/// Use `clock` (milliseconds, any origin) for command durations.
pub fn set_clock(clock: fn() -> f64) {
*CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(clock);
}
fn now_ms() -> Option<f64> {
if let Some(c) = *CLOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
return Some(c());
}
#[cfg(not(target_arch = "wasm32"))]
{
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
Some(START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1000.0)
}
#[cfg(target_arch = "wasm32")]
None
}
thread_local! {
/// Commands running on this thread: only the outermost is counted.
static DEPTH: Cell<u32> = const { Cell::new(0) };
}
/// A command being counted, from [`Session::execute`](crate::Session::execute): `None` when it
/// is not (not recording, no origin, or a command inside another).
pub(crate) struct Timer {
started: Option<f64>,
from: Option<Origin>,
}
impl Timer {
pub(crate) fn start(from: Option<Origin>) -> Timer {
let outer = DEPTH.with(|d| {
d.set(d.get() + 1);
d.get() == 1
});
let from = from.filter(|_| outer && enabled());
Timer { started: from.and_then(|_| now_ms()), from }
}
/// Whether this command is counted.
pub(crate) fn counting(&self) -> bool {
self.from.is_some()
}
/// The command ended: count it, and the milestone it reached.
pub(crate) fn done(
&self,
command: &'static str,
kind: CommandKind,
error: Option<&EngineError>,
milestone: Option<Milestone>,
sample: Option<&'static str>,
) {
let Some(from) = self.from else { return };
let duration_ms = match (self.started, now_ms()) {
(Some(a), Some(b)) if b >= a => (b - a).round() as u64,
_ => 0,
};
record(Event::CommandRun { command, kind, duration_ms, error: error.map(error_class), from });
if error.is_none() {
if let Some(m) = milestone {
record(Event::Milestone(m));
}
if let Some(name) = sample {
record(Event::SampleOpened { name });
}
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
/// The milestone a successful `command` reaches; `elements` is the element count before and
/// after it.
pub(crate) fn milestone(command: &str, elements: (usize, usize)) -> Option<Milestone> {
match command {
"geometry.open" | "geometry.import.mesh" | "file.open" => Some(Milestone::DesignOpened),
c if c.starts_with("mesh.") && elements.1 > elements.0 => Some(Milestone::Meshed),
// Solvers, not the queries on a solved step.
c if c.starts_with("solve.") && !matches!(c, "solve.probe" | "solve.history") => Some(Milestone::Solved),
c if c.starts_with("results.") && !matches!(c, "results.reactions" | "results.clear") => Some(Milestone::ResultsViewed),
_ => None,
}
}
/// Serialises the tests (and other code) that turn the process-wide recording on.
#[doc(hidden)]
pub static TEST_LOCK: Mutex<()> = Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
use crate::Session;
fn identity() -> Identity {
Identity { install_id: "00000000-0000-4000-8000-000000000000".into(), platform: "desktop", os: "test", arch: "test", app_version: "0.0.0" }
}
fn take_all() -> Vec<Event> {
std::iter::from_fn(take_batch).flat_map(|b| b.events).collect()
}
/// Every string in a payload is a key, a registry name or the identity, and every number a
/// duration: no path, file name, parameter value or message can be in it.
pub(crate) fn assert_clean(body: &str) {
let v: Value = serde_json::from_str(body).unwrap();
let mut allowed: Vec<String> = crate::commands().iter().map(|c| c.id.to_string()).collect();
allowed.extend(crate::sample::SAMPLES.iter().map(|s| s.name.to_string()));
for e in [
"app_started",
"app_closed",
"command_run",
"milestone",
"sample_opened",
"form_cancelled",
"unavailable_clicked",
"model",
"session",
"ui",
"palette",
"script",
"mcp",
"design_opened",
"meshed",
"solved",
"results_viewed",
"unknown_command",
"params",
"geometry",
"mesh",
"file",
"deck",
"solver",
"explicit",
"fluid",
"unavailable",
"internal",
"KEY",
] {
allowed.push(e.into());
}
let id = identity();
allowed.extend([id.install_id, id.platform.into(), id.os.into(), id.arch.into(), id.app_version.into()]);
fn walk(key: &str, v: &Value, allowed: &[String]) {
match v {
Value::String(s) => {
// A requirement's snake_case name.
let requirement = key == "missing" && s.chars().all(|c| c.is_ascii_lowercase() || c == '_');
assert!(allowed.contains(s) || requirement, "`{key}`: `{s}` is not a name FieldCraft defines");
}
Value::Number(_) => assert!(["duration_ms", "duration_s"].contains(&key), "`{key}`: a number that is not a duration"),
Value::Array(a) => a.iter().for_each(|x| walk(key, x, allowed)),
Value::Object(m) => m.iter().for_each(|(k, x)| walk(k, x, allowed)),
Value::Bool(_) | Value::Null => {}
}
}
walk("", &v, &allowed);
}
#[test]
fn nothing_is_queued_without_consent() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
let mut s = Session { origin: Some(Origin::Ui), ..Default::default() };
s.run_script(&crate::sample::cantilever()).unwrap();
record(Event::AppStarted);
assert_eq!(queued(), 0);
assert!(take_batch().is_none());
}
#[test]
fn a_scripted_session_sends_only_names_and_durations() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
enable(identity(), true);
let dir = std::env::temp_dir().join(format!("fieldcraft-usage-secret-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let design = dir.join("my-secret-bracket.solidcraft");
std::fs::write(&design, fieldcraft_geometry::sample::plate_design(&fieldcraft_geometry::sample::Plate::default()).unwrap()).unwrap();
let mut s = Session { origin: Some(Origin::Script), ..Default::default() };
s.execute("geometry.open", &json!({"path": design.to_string_lossy()})).unwrap();
s.run_script(&crate::sample::cantilever()).unwrap();
s.execute("model.material.create", &json!({"name": "Secret alloy 7", "elastic": {"young": 123456.75, "poisson": 0.3125}})).ok();
s.execute("solve.run", &json!({})).unwrap();
s.execute("results.contour", &json!({"field": "von_mises"})).unwrap();
// A failure whose message names a path, and a sample.
assert!(s.execute("file.open", &json!({"path": dir.join("missing-secret.fieldcraft").to_string_lossy()})).is_err());
s.execute("file.sample", &json!({"name": "cantilever"})).unwrap();
// An unknown id is user text: not counted.
assert!(s.execute("secret.command", &json!({})).is_err());
let events = take_all();
let body = Batch { identity: identity(), events: events.clone() }.body("KEY");
assert_clean(&body);
for secret in ["secret", "Secret", "123456", "0.3125", "1000", dir.to_string_lossy().as_ref()] {
assert!(!body.contains(secret), "{secret} in {body}");
}
let names: Vec<&str> = events.iter().map(Event::name).collect();
assert!(names.contains(&"command_run") && names.contains(&"sample_opened"), "{names:?}");
// Inner commands (the script's steps run by execute, a sample's own script) count once.
let runs = events.iter().filter(|e| matches!(e, Event::CommandRun { command: "file.sample", .. })).count();
assert_eq!(runs, 1);
let reached: Vec<_> = events.iter().filter_map(|e| if let Event::Milestone(m) = e { Some(*m) } else { None }).collect();
for m in [Milestone::DesignOpened, Milestone::Meshed, Milestone::Solved, Milestone::ResultsViewed] {
assert_eq!(reached.iter().filter(|r| **r == m).count(), 1, "{m:?} once: {reached:?}");
}
assert!(
events.iter().any(|e| matches!(e, Event::CommandRun { command: "file.open", error: Some("file"), from: Origin::Script, .. })),
"{events:?}"
);
disable();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn scripts_and_agents_can_be_left_out_and_the_queue_is_bounded() {
let _g = TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
disable();
enable(identity(), false);
let run = |from| Event::CommandRun { command: "model.info", kind: CommandKind::Model, duration_ms: 1, error: None, from };
record(run(Origin::Mcp));
record(run(Origin::Script));
record(run(Origin::Palette));
assert_eq!(take_all(), [Event::AppStarted, run(Origin::Palette)]);
for _ in 0..MAX_QUEUED + 50 {
record(Event::AppStarted);
}
assert_eq!(queued(), MAX_QUEUED);
let first = take_batch().unwrap();
assert_eq!(first.events.len(), MAX_BATCH);
assert_eq!(queued(), MAX_QUEUED - MAX_BATCH);
// Turning it off drops what waits.
disable();
assert_eq!(queued(), 0);
enable(identity(), true);
closing();
assert!(matches!(take_all()[..], [Event::AppStarted, Event::AppClosed { .. }]));
disable();
}
#[test]
fn the_body_is_a_posthog_batch() {
let b = Batch {
identity: identity(),
events: vec![Event::UnavailableClicked { command: "solve.run", missing: vec![Requirement::Step, Requirement::Material] }],
};
let v: Value = serde_json::from_str(&b.body("phc_test")).unwrap();
assert_eq!(v["api_key"], "phc_test");
let e = &v["batch"][0];
assert_eq!((e["event"].as_str(), e["distinct_id"].as_str()), (Some("unavailable_clicked"), Some(identity().install_id.as_str())));
assert_eq!(e["properties"]["missing"], json!(["step", "material"]));
assert_eq!(e["properties"]["$process_person_profile"], false);
assert_eq!(e["properties"]["$geoip_disable"], true);
assert_clean(&b.body("KEY"));
}
#[test]
fn telemetry_is_off_without_a_key_in_automation_and_ci_and_when_turned_off() {
assert!(allowed(true, None, false, false));
assert!(!allowed(false, None, false, false));
assert!(!allowed(false, Some("1"), false, false));
assert!(!allowed(true, Some("0"), false, false));
assert!(!allowed(true, Some(" off "), false, false));
assert!(!allowed(true, None, true, false));
assert!(!allowed(true, None, false, true));
assert!(!allowed(true, Some(""), true, false));
assert!(allowed(true, Some("1"), true, true));
}
}
+113 -28
View File
@@ -8,11 +8,11 @@
//! deformed shape (automatic or chosen scale) with its contour bands. Animation is not drawn: a
//! picture shows the full deformation (a mode at its positive shape). The analysis setup's
//! symbols ([`fieldcraft_render::glyphs`]) are drawn over the model as the viewport draws them,
//! muted over a results plot.
//! muted over a results plot, at their default size on screen once the camera is known.
use fieldcraft_model::ElementKind;
use fieldcraft_render::contour::{Bands, band_color, split_triangle};
use fieldcraft_render::glyphs::{GlyphColors, GlyphShow, Glyphs};
use fieldcraft_render::glyphs::{self, GlyphColors, GlyphShow, GlyphView, Glyphs};
use fieldcraft_render::{Aabb3, Camera, DisplayMesh, Orientation, Rgb, Scene, SceneLine, SceneTri, Vec3};
use serde_json::Value;
@@ -72,6 +72,9 @@ impl Palette {
interaction: Rgb(0x9a, 0x30, 0xc0),
thermal: Rgb(0xe8, 0x4c, 0x00),
label: Rgb(0x26, 0x2a, 0x32),
datum: Rgb(0x1e, 0x8c, 0x6e),
contact: Rgb(0x6a, 0x8a, 0x00),
highlight: Rgb(0xd6, 0x00, 0x7f),
},
};
@@ -118,14 +121,14 @@ pub struct Shown {
pub fn display(s: &Session) -> (DisplayMesh, Vec<String>) {
let mut d = DisplayMesh::from_model(&s.model);
let mut failed = Vec::new();
for body in s.design.iter().flat_map(|d| &d.bodies) {
for body in s.design.iter().flat_map(|d| &d.bodies).filter(|b| s.shows(fieldcraft_io::ItemKind::Body, &b.name)) {
let mesh = body.measure().and_then(|m| body.tessellate(display_tolerance(&Aabb3 { min: m.bbox_min.into(), max: m.bbox_max.into() })));
match mesh {
Ok(m) => d.add_surface(&m.positions, &m.triangles, &m.tri_face),
Err(e) => failed.push(format!("{}: {e}", body.name)),
}
}
for surface in &s.surfaces {
for surface in s.surfaces.iter().filter(|x| s.shows(fieldcraft_io::ItemKind::Surface, &x.name)) {
d.add_surface(&surface.mesh.positions, &surface.mesh.triangles, &surface.mesh.tri_face);
}
(d, failed)
@@ -140,23 +143,54 @@ fn model_scene(d: &DisplayMesh, p: &Palette) -> Scene {
s.tris.extend(d.surface_tris.iter().map(|t| SceneTri { p: t.p, normal: t.normal, color: d.body_color(t, p.geometry, &p.bodies) }));
}
s.lines = d.edges.iter().map(|e| SceneLine { a: e.p[0], b: e.p[1], color: p.mesh_edge, width: EDGE_WIDTH }).collect();
let edge = if faces_drawn { p.mesh_edge } else { p.geometry_edge };
s.lines.extend(d.surface_edges.iter().map(|[a, b]| SceneLine { a: *a, b: *b, color: edge, width: GEOMETRY_EDGE_WIDTH }));
if faces_drawn {
s.lines.extend(d.surface_edges.iter().map(|[a, b]| SceneLine { a: *a, b: *b, color: p.mesh_edge, width: GEOMETRY_EDGE_WIDTH }));
} else {
// Over the mesh the geometry's edges are drawn along it (the element edges on them), so
// they lie on the element faces.
let edge = p.geometry_edge;
s.lines.extend(d.edges.iter().filter(|e| e.feature).map(|e| SceneLine { a: e.p[0], b: e.p[1], color: edge, width: GEOMETRY_EDGE_WIDTH }));
}
s.lines.extend(d.lines.iter().map(|l| SceneLine { a: l.a, b: l.b, color: p.element(l.kind), width: LINE_ELEMENT_WIDTH }));
s
}
/// The scene of the session: the model, or the results view's plot, and what it shows.
pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
/// The model part of a picture: the model or the results view's plot, the shape the symbols sit
/// on (the deformed one of a plot), the box around it and what it shows.
struct Picture {
scene: Scene,
drawn: DisplayMesh,
bounds: Aabb3,
shown: Shown,
glyphs: Glyphs,
colors: GlyphColors,
/// The box around the datums drawn: inside the clipping radius, never framed (#295).
datums: Aabb3,
}
impl Picture {
/// The setup's symbols at symbol unit `unit` ([`glyphs::symbol_unit`]), in a scene of their
/// own; notes the definitions drawn with a sample. Returns the box around them.
fn symbols(&mut self, unit: f64, into: &mut Scene) -> Aabb3 {
let drawn = &self.drawn;
let view = GlyphView { show: GlyphShow::ALL, colors: &self.colors, unit, highlight: None };
let d = self.glyphs.draw(|label| drawn.node_position(label), &view, into);
self.shown.sampled = d.notes;
d.bounds
}
}
fn picture(s: &Session, p: &Palette) -> Picture {
let (base, failed) = display(s);
let glyphs = Glyphs::from_model(&s.model);
let mut shown = Shown { failed, sampled: glyphs.notes.clone(), ..Shown::default() };
let glyphs = s.glyphs();
let mut shown = Shown { failed, ..Shown::default() };
let plot = s.results_view.as_ref().and_then(|v| s.latest_result(&v.step).map(|(r, _)| (v, r)));
let Some((view, result)) = plot else {
let mut bounds = base.bounds;
let mut scene = model_scene(&base, p);
bounds.union(glyphs.draw(|label| base.node_position(label), GlyphShow::ALL, &p.glyphs, &mut scene));
return (scene, bounds, shown);
let bounds = base.bounds;
let shows = |n: &str| s.shows(fieldcraft_io::ItemKind::Datum, n);
let datums = fieldcraft_render::glyphs::datums(&s.model, &base.bounds, &shows, None, &p.glyphs, &mut scene);
return Picture { scene, drawn: base, bounds, shown, glyphs, colors: p.glyphs, datums };
};
shown.step = Some(view.step.clone());
let pick = view.pick();
@@ -198,11 +232,21 @@ pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
});
}
}
let symbols = glyphs.draw(|label| drawn.node_position(label), GlyphShow::ALL, &p.glyphs.over_results(p.background.1), &mut scene);
let mut bounds = base.bounds;
bounds.union(drawn.bounds);
bounds.union(symbols);
(scene, bounds, shown)
Picture { scene, drawn, bounds, shown, glyphs, colors: p.glyphs.over_results(p.background.1), datums: Aabb3::EMPTY }
}
/// The scene of the session (the model, or the results view's plot) with the setup's symbols
/// at the model's own symbol unit, the box around it, and what it shows.
pub fn scene(s: &Session, p: &Palette) -> (Scene, Aabb3, Shown) {
let mut pic = picture(s, p);
let mut symbols = Scene::default();
let b = pic.symbols(pic.glyphs.model_unit(), &mut symbols);
let mut scene = pic.scene;
scene.append(symbols);
pic.bounds.union(b);
(scene, pic.bounds, pic.shown)
}
/// A camera orientation from JSON, `{"yaw": …, "pitch": …, "distance"?: …}`: degrees, and the
@@ -222,17 +266,31 @@ pub fn orientation(p: &Value) -> Result<Orientation> {
Orientation::checked(yaw, pitch, distance).ok_or_else(|| bad("`yaw` and `pitch` must be finite and `distance` finite and above 0"))
}
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn, or from
/// `at`'s distance when it has one.
/// A PNG of the session seen from `at`, `w` × `h` pixels: framing everything drawn but the
/// datums (they are drawn at the model's extent, and framing them would only add margin), or from
/// `at`'s distance when it has one. The symbols are drawn at their default size on screen
/// ([`glyphs::DEFAULT_SIZE`] pixels) for that camera.
pub fn render_png(s: &Session, at: &Orientation, w: usize, h: usize, p: &Palette) -> Result<(Vec<u8>, Shown)> {
let (mut scene, bounds, shown) = scene(s, p);
let mut pic = picture(s, p);
let mut cam = Camera::default();
let aspect = w as f64 / h.max(1) as f64;
let unit = |cam: &Camera| cam.length_per_pixel(h as f64).and_then(|l| glyphs::symbol_unit(l, glyphs::DEFAULT_SIZE)).unwrap_or(f64::NAN);
// Framed on the model, then again with its symbols at that camera's size, which reach a
// little beyond it.
cam.orient(&Orientation { distance: None, ..*at });
cam.fit(&bounds);
cam.fit_in(&pic.bounds, aspect, fieldcraft_render::FULL_VIEW);
let mut symbols = Scene::default();
let mut framed = pic.bounds;
framed.union(pic.symbols(unit(&cam), &mut symbols));
cam.fit_in(&framed, aspect, fieldcraft_render::FULL_VIEW);
cam.orient(at);
scene.radius = if bounds.is_empty() { 1.0 } else { (cam.target.dist(bounds.center()) + bounds.diagonal() * 0.5).max(1e-3) };
let png = fieldcraft_render::render_png(&scene, &cam, w, h).map_err(|e| EngineError::Params(format!("render: {e}")))?;
Ok((png, shown))
symbols = Scene::default();
let mut bounds = pic.bounds;
bounds.union(pic.symbols(unit(&cam), &mut symbols));
bounds.union(pic.datums);
pic.scene.radius = if bounds.is_empty() { 1.0 } else { (cam.target.dist(bounds.center()) + bounds.diagonal() * 0.5).max(1e-3) };
let png = fieldcraft_render::render_layers_png(&pic.scene, &[&symbols], &cam, w, h).map_err(|e| EngineError::Params(format!("render: {e}")))?;
Ok((png, pic.shown))
}
#[cfg(test)]
@@ -251,14 +309,19 @@ mod tests {
s.run_script(&crate::sample::cantilever()).unwrap();
let (model, shown) = render_png(&s, &iso, 64, 48, &Palette::LIGHT).unwrap();
assert_eq!(shown, Shown::default());
// The clamp's cones and the push's arrows are drawn in their colours.
// The clamp's triangles and the push's arrows are drawn in their colours, as wireframes.
let (scene, ..) = super::scene(&s, &Palette::LIGHT);
assert!(scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
assert!(scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.constraint));
assert!(scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.load));
assert!(!scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
// And in the picture: pixels of the clamp's colour.
let (png, _) = render_png(&s, &iso, 320, 240, &Palette::LIGHT).unwrap();
assert!(count_color(&png, Palette::LIGHT.glyphs.constraint) > 20);
s.execute("solve.static", &json!({})).unwrap();
let (plot, shown) = render_png(&s, &iso, 64, 48, &Palette::LIGHT).unwrap();
assert_ne!(model, plot);
assert!(shown.scale > 0.0 && shown.step.is_some(), "{shown:?}");
// A static step first shows its contours on the undeformed shape.
assert!(shown.scale == 0.0 && shown.step.is_some(), "{shown:?}");
let (field, min, max) = shown.contour.unwrap();
assert_eq!(field, "von_mises");
assert!(max.1 > min.1);
@@ -266,8 +329,30 @@ mod tests {
// Over the plot the symbols are muted.
let (scene, ..) = super::scene(&s, &Palette::LIGHT);
let muted = Palette::LIGHT.glyphs.over_results(Palette::LIGHT.background.1);
assert!(scene.tris.iter().any(|t| t.color == muted.constraint));
assert!(!scene.tris.iter().any(|t| t.color == Palette::LIGHT.glyphs.constraint));
assert!(scene.lines.iter().any(|l| l.color == muted.constraint));
assert!(!scene.lines.iter().any(|l| l.color == Palette::LIGHT.glyphs.constraint));
}
/// Pixels of colour `c` (within a few levels) in a PNG.
fn count_color(png: &[u8], c: Rgb) -> usize {
let d = png::Decoder::new(std::io::Cursor::new(png));
let mut r = d.read_info().unwrap();
let mut buf = vec![0; r.output_buffer_size().unwrap()];
let info = r.next_frame(&mut buf).unwrap();
let close = |a: u8, b: u8| a.abs_diff(b) <= 6;
buf[..info.buffer_size()].chunks(4).filter(|p| close(p[0], c.0) && close(p[1], c.1) && close(p[2], c.2)).count()
}
/// The symbols are as large on screen in a close-up as in a distant view.
#[test]
fn symbols_keep_their_size_in_pictures_at_any_distance() {
let mut s = Session::default();
s.run_script(&crate::sample::cantilever()).unwrap();
let at = |d: f64| orientation(&json!({"yaw": -45, "pitch": 30, "distance": d})).unwrap();
let clamp = |d: f64| count_color(&render_png(&s, &at(d), 400, 300, &Palette::LIGHT).unwrap().0, Palette::LIGHT.glyphs.constraint);
let (near, far) = (clamp(120.0), clamp(1200.0));
// Zoomed out ten times, the symbols are as large (a few overlap and thin out).
assert!(far > 30 && far * 4 > near, "near {near}, far {far}");
}
#[test]
+3
View File
@@ -215,6 +215,9 @@ impl System {
if let Some(name) = model.couplings().keys().next() {
return Err(Error::NotSupported(format!("couplings (coupling `{name}`) in explicit dynamics")));
}
if let Some(name) = model.ties().keys().next() {
return Err(Error::NotSupported(format!("ties (tie `{name}`) in explicit dynamics")));
}
// Elements by label, with their section's material.
let mut materials: Vec<Material> = Vec::new();
+341
View File
@@ -0,0 +1,341 @@
//! Forward-mode automatic differentiation in [`VARS`] variables, for kernels whose exact first
//! and second derivatives are too long to write by hand (the mortar contact integrals of
//! [`crate::mortar`], whose segmentation moves with the nodes).
//!
//! A kernel is written once over a [`Real`] scalar and run on `f64` for its value, on [`Dual`]
//! for its gradient, or on [`Hyper`] for its gradient and Hessian. Arithmetic propagates the
//! derivatives by the chain rule (truncated Taylor arithmetic: A. Griewank, A. Walther,
//! *Evaluating Derivatives*, 2nd ed., SIAM 2008, ch. 3 and 13), so the derivatives are those of
//! the code as it runs, to round-off: the branches a kernel takes (which polygon edges clip,
//! which root of a quadratic) are decided on the values and differentiated where they are
//! taken, which is the derivative of the piecewise smooth function wherever it is smooth. The
//! automated linearisation of contact kernels this way is that of J. Lengiewicz, J. Korelc, S.
//! Stupkiewicz, *Automation of finite element formulations for large deformation contact
//! problems*, IJNME 85:1252–1279, 2011.
//!
//! [`jet::Jet`](crate::jet::Jet) is the three-variable sibling the shape-function library uses.
use std::ops::{Add, Div, Mul, Neg, Sub};
/// Independent variables of [`Dual`] and [`Hyper`]: the corners of two faces of up to four
/// nodes, three coordinates each.
pub const VARS: usize = 24;
/// Entries of a packed symmetric [`VARS`] × [`VARS`] Hessian (its upper triangle by rows).
pub const PACKED: usize = VARS * (VARS + 1) / 2;
/// The position of (i, j) in a packed upper triangle (either order).
pub fn packed(i: usize, j: usize) -> usize {
let (a, b) = if i <= j { (i, j) } else { (j, i) };
// Row a starts after rows 0..a, of VARS, VARS − 1, … entries.
a * VARS - a * a.saturating_sub(1) / 2 + (b - a)
}
/// A scalar a kernel can be written over: `f64`, [`Dual`] or [`Hyper`].
pub trait Real:
Copy
+ Add<Output = Self>
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
+ Neg<Output = Self>
+ Add<f64, Output = Self>
+ Sub<f64, Output = Self>
+ Mul<f64, Output = Self>
{
/// A constant.
fn cst(v: f64) -> Self;
/// The value.
fn val(&self) -> f64;
fn sqrt(self) -> Self;
}
impl Real for f64 {
fn cst(v: f64) -> f64 {
v
}
fn val(&self) -> f64 {
*self
}
fn sqrt(self) -> f64 {
f64::sqrt(self)
}
}
/// A value and its gradient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Dual {
pub v: f64,
pub g: [f64; VARS],
}
impl Dual {
/// Variable `k` at value `v` (a constant when `k` is out of range).
pub fn var(v: f64, k: usize) -> Dual {
let mut d = Dual::cst(v);
if let Some(g) = d.g.get_mut(k) {
*g = 1.0;
}
d
}
fn chain(self, v: f64, d: f64) -> Dual {
Dual { v, g: self.g.map(|x| d * x) }
}
}
impl Real for Dual {
fn cst(v: f64) -> Dual {
Dual { v, g: [0.0; VARS] }
}
fn val(&self) -> f64 {
self.v
}
fn sqrt(self) -> Dual {
let s = self.v.sqrt();
self.chain(s, 0.5 / s)
}
}
impl Add for Dual {
type Output = Dual;
fn add(mut self, o: Dual) -> Dual {
self.v += o.v;
self.g.iter_mut().zip(o.g).for_each(|(a, b)| *a += b);
self
}
}
impl Sub for Dual {
type Output = Dual;
fn sub(mut self, o: Dual) -> Dual {
self.v -= o.v;
self.g.iter_mut().zip(o.g).for_each(|(a, b)| *a -= b);
self
}
}
impl Mul for Dual {
type Output = Dual;
fn mul(self, o: Dual) -> Dual {
let mut g = [0.0; VARS];
for k in 0..VARS {
g[k] = self.v * o.g[k] + o.v * self.g[k];
}
Dual { v: self.v * o.v, g }
}
}
impl Div for Dual {
type Output = Dual;
fn div(self, o: Dual) -> Dual {
let r = 1.0 / o.v;
let v = self.v * r;
let mut g = [0.0; VARS];
for k in 0..VARS {
g[k] = (self.g[k] - v * o.g[k]) * r;
}
Dual { v, g }
}
}
impl Neg for Dual {
type Output = Dual;
fn neg(self) -> Dual {
Dual { v: -self.v, g: self.g.map(|x| -x) }
}
}
impl Add<f64> for Dual {
type Output = Dual;
fn add(mut self, o: f64) -> Dual {
self.v += o;
self
}
}
impl Sub<f64> for Dual {
type Output = Dual;
fn sub(mut self, o: f64) -> Dual {
self.v -= o;
self
}
}
impl Mul<f64> for Dual {
type Output = Dual;
fn mul(self, o: f64) -> Dual {
Dual { v: self.v * o, g: self.g.map(|x| x * o) }
}
}
/// A value, its gradient and its Hessian (packed upper triangle, [`packed`]).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Hyper {
pub v: f64,
pub g: [f64; VARS],
pub h: [f64; PACKED],
}
impl Hyper {
/// Variable `k` at value `v` (a constant when `k` is out of range).
pub fn var(v: f64, k: usize) -> Hyper {
let mut d = Hyper::cst(v);
if let Some(g) = d.g.get_mut(k) {
*g = 1.0;
}
d
}
/// ∂²/∂x_i∂x_j.
pub fn hessian(&self, i: usize, j: usize) -> f64 {
self.h.get(packed(i, j)).copied().unwrap_or(0.0)
}
/// f(self) from f's value `f0`, first derivative `f1` and second derivative `f2` at the
/// value: g = f1 g, H = f1 H + f2 g gᵀ.
fn chain(&self, f0: f64, f1: f64, f2: f64) -> Hyper {
let mut out = Hyper { v: f0, g: self.g.map(|x| f1 * x), h: [0.0; PACKED] };
let mut at = 0;
for i in 0..VARS {
let gi = f2 * self.g[i];
for j in i..VARS {
out.h[at] = f1 * self.h[at] + gi * self.g[j];
at += 1;
}
}
out
}
}
impl Real for Hyper {
fn cst(v: f64) -> Hyper {
Hyper { v, g: [0.0; VARS], h: [0.0; PACKED] }
}
fn val(&self) -> f64 {
self.v
}
fn sqrt(self) -> Hyper {
let s = self.v.sqrt();
self.chain(s, 0.5 / s, -0.25 / (s * s * s))
}
}
impl Add for Hyper {
type Output = Hyper;
fn add(mut self, o: Hyper) -> Hyper {
self.v += o.v;
self.g.iter_mut().zip(&o.g).for_each(|(a, b)| *a += b);
self.h.iter_mut().zip(&o.h).for_each(|(a, b)| *a += b);
self
}
}
impl Sub for Hyper {
type Output = Hyper;
fn sub(mut self, o: Hyper) -> Hyper {
self.v -= o.v;
self.g.iter_mut().zip(&o.g).for_each(|(a, b)| *a -= b);
self.h.iter_mut().zip(&o.h).for_each(|(a, b)| *a -= b);
self
}
}
impl Mul for Hyper {
type Output = Hyper;
fn mul(self, o: Hyper) -> Hyper {
let mut out = Hyper { v: self.v * o.v, g: [0.0; VARS], h: [0.0; PACKED] };
for k in 0..VARS {
out.g[k] = self.v * o.g[k] + o.v * self.g[k];
}
let mut at = 0;
for i in 0..VARS {
let (a, b) = (self.g[i], o.g[i]);
for j in i..VARS {
out.h[at] = self.v * o.h[at] + o.v * self.h[at] + a * o.g[j] + b * self.g[j];
at += 1;
}
}
out
}
}
impl Div for Hyper {
type Output = Hyper;
fn div(self, o: Hyper) -> Hyper {
let r = 1.0 / o.v;
self * o.chain(r, -r * r, 2.0 * r * r * r)
}
}
impl Neg for Hyper {
type Output = Hyper;
fn neg(self) -> Hyper {
Hyper { v: -self.v, g: self.g.map(|x| -x), h: self.h.map(|x| -x) }
}
}
impl Add<f64> for Hyper {
type Output = Hyper;
fn add(mut self, o: f64) -> Hyper {
self.v += o;
self
}
}
impl Sub<f64> for Hyper {
type Output = Hyper;
fn sub(mut self, o: f64) -> Hyper {
self.v -= o;
self
}
}
impl Mul<f64> for Hyper {
type Output = Hyper;
fn mul(self, o: f64) -> Hyper {
Hyper { v: self.v * o, g: self.g.map(|x| x * o), h: self.h.map(|x| x * o) }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn f<T: Real>(x: T, y: T) -> T {
(x * x * y + T::cst(1.0)).sqrt() / (y - x * 0.5) + x * 3.0
}
#[test]
fn packed_indices_cover_the_upper_triangle_once() {
let mut seen = vec![false; PACKED];
let mut at = 0;
for i in 0..VARS {
for j in i..VARS {
assert_eq!(packed(i, j), at);
assert_eq!(packed(j, i), at);
seen[at] = true;
at += 1;
}
}
assert!(seen.iter().all(|s| *s));
}
#[test]
fn derivatives_match_finite_differences() {
let (x, y) = (0.7, 2.3);
let h = 1e-5;
let fx = |x: f64, y: f64| f(x, y);
let gx = (fx(x + h, y) - fx(x - h, y)) / (2.0 * h);
let gy = (fx(x, y + h) - fx(x, y - h)) / (2.0 * h);
let hxy = (fx(x + h, y + h) - fx(x + h, y - h) - fx(x - h, y + h) + fx(x - h, y - h)) / (4.0 * h * h);
let hxx = (fx(x + h, y) - 2.0 * fx(x, y) + fx(x - h, y)) / (h * h);
let d = f(Dual::var(x, 3), Dual::var(y, 17));
assert!((d.v - fx(x, y)).abs() < 1e-14 && (d.g[3] - gx).abs() < 1e-8 && (d.g[17] - gy).abs() < 1e-8);
let e = f(Hyper::var(x, 3), Hyper::var(y, 17));
assert!((e.g[3] - gx).abs() < 1e-8 && (e.g[17] - gy).abs() < 1e-8);
assert!((e.hessian(3, 17) - hxy).abs() < 1e-4 && (e.hessian(17, 3) - hxy).abs() < 1e-4, "{} {hxy}", e.hessian(3, 17));
assert!((e.hessian(3, 3) - hxx).abs() < 1e-3);
assert_eq!(e.hessian(0, 5), 0.0);
}
}
+155 -12
View File
@@ -515,6 +515,21 @@ impl Plane<'_> {
}
}
/// The kinematics of one point of a 2D element in a nonlinear step: F, det F_m, the volume share, the strain columns (current at finite strain), the small strain,
/// the temperature and the reference position.
struct PlaneKinematics {
f: Mat3,
/// det F_m (small strain: 1), and the dilatation the mixed element averages (small strain:
/// 1 + tr ε).
j: f64,
dilatation: f64,
dv: f64,
current: Vec<[f64; 3]>,
strain: [f64; 6],
heat: Heat,
x: [f64; 3],
}
/// One integration point of a 2D element in a nonlinear step: the total deformation gradient,
/// det F_m, the reference position and the response.
struct PlanePoint {
@@ -525,8 +540,14 @@ struct PlanePoint {
}
impl Plane<'_> {
fn check_nonlinear(&self, u: &[[f64; 2]], kin: Kinematics) -> Result<()> {
fn check_nonlinear(&self, m: &MaterialModel, u: &[[f64; 2]], kin: Kinematics) -> Result<()> {
check_displacements(u, self.ty.nodes)?;
if matches!(self.formulation, Formulation::Hybrid { .. }) && !m.is_decoupled() {
return Err(Error::NotSupported(format!(
"hybrid elements of a {} material in nonlinear steps (the mixed formulation needs a volumetric–isochoric split of the strain energy; give the material the neo-Hookean option)",
m.name()
)));
}
if let Theory::PlaneStress { .. } = self.theory {
let why = match kin {
Kinematics::Finite => "the thickness change needs a local iteration",
@@ -558,7 +579,7 @@ impl Plane<'_> {
updated: &mut [f64],
tangent: bool,
) -> Result<(Finite, Vec<PlanePoint>)> {
self.check_nonlinear(u, kin)?;
self.check_nonlinear(m, u, kin)?;
let n = self.ty.nodes;
if let Some(t) = thermal {
t.check(n)?;
@@ -570,8 +591,9 @@ impl Plane<'_> {
let mut k = tangent.then(|| Matrix::zeros(ndof));
let axisymmetric = self.theory == Theory::Axisymmetric;
let small = kin == Kinematics::Small;
let mut out = Vec::with_capacity(rule.len());
for (i, p) in rule.iter().enumerate() {
// The kinematics of every point first: the mixed element's pressure needs them all.
let mut kinematics = Vec::with_capacity(rule.len());
for p in &rule {
let at = self.at(p)?;
let cols = at.g.get(..n).unwrap_or_default();
let mut f = IDENTITY;
@@ -585,12 +607,11 @@ impl Plane<'_> {
f[2][2] += ua[0] * g[2];
}
}
let updated_point = updated.get_mut(i * len..(i + 1) * len).unwrap_or_default();
let heat = Heat::at(thermal, at.shape.values())?;
let (j, dv, current, r) = if small {
let point = if small {
let strain = heat.mechanical_strain(&small_strain(&f));
let r = m.small_strain(&strain, heat.temperature, point_history(committed, len, i), updated_point, true)?;
(1.0, at.dv, cols.to_vec(), r)
let volume = 1.0 + strain[0] + strain[1] + strain[2];
PlaneKinematics { f, j: 1.0, dilatation: volume, dv: at.dv, current: cols.to_vec(), strain, heat, x: at.x }
} else {
let det2 = f[0][0] * f[1][1] - f[0][1] * f[1][0];
let j = det2 * f[2][2];
@@ -600,9 +621,29 @@ impl Plane<'_> {
let inv = [[f[1][1] / det2, -f[0][1] / det2], [-f[1][0] / det2, f[0][0] / det2]];
let current: Vec<[f64; 3]> =
cols.iter().map(|g| [g[0] * inv[0][0] + g[1] * inv[1][0], g[0] * inv[0][1] + g[1] * inv[1][1], g[2] / f[2][2]]).collect();
let r = m.response(&heat.mechanical(&f), heat.temperature, point_history(committed, len, i), updated_point)?;
(j / heat.volume(), at.dv * heat.volume(), current, r)
let j = j / heat.volume();
PlaneKinematics { f, j, dilatation: j, dv: at.dv * heat.volume(), current, strain: [0.0; 6], heat, x: at.x }
};
kinematics.push(point);
}
let responses: Vec<Response> = if let Formulation::Hybrid { .. } = self.formulation {
self.mean_dilatation(m, &kinematics, small, committed, updated, k.as_mut())?
} else {
let mut out = Vec::with_capacity(kinematics.len());
for (i, p) in kinematics.iter().enumerate() {
let updated_point = updated.get_mut(i * len..(i + 1) * len).unwrap_or_default();
let history = point_history(committed, len, i);
out.push(if small {
m.small_strain(&p.strain, p.heat.temperature, history, updated_point, true)?
} else {
m.response(&p.heat.mechanical(&p.f), p.heat.temperature, history, updated_point)?
});
}
out
};
let mut out = Vec::with_capacity(rule.len());
for (p, r) in kinematics.into_iter().zip(responses) {
let (dv, current) = (p.dv, &p.current);
let tau = [r.stress[0], r.stress[1], r.stress[2], r.stress[3]];
for (a, g) in current.iter().enumerate() {
if let Some(x) = force.get_mut(2 * a) {
@@ -614,7 +655,7 @@ impl Plane<'_> {
}
if let Some(k) = k.as_mut() {
let c4: [[f64; 4]; 4] = std::array::from_fn(|a| std::array::from_fn(|b| r.tangent[a][b]));
crate::plane::accumulate(&mut k.data, &current, &c4, dv);
crate::plane::accumulate(&mut k.data, current, &c4, dv);
if !small {
for (a, ga) in current.iter().enumerate() {
for (b, gb) in current.iter().enumerate() {
@@ -625,11 +666,56 @@ impl Plane<'_> {
}
}
}
out.push(PlanePoint { f, j, x: at.x, response: r });
out.push(PlanePoint { f: p.f, j: p.j, x: p.x, response: r });
}
Ok((Finite { force, tangent: k }, out))
}
/// The mean dilatation responses of a hybrid 2D element (one constant pressure): θ = ∫ J dV₀
/// / V₀ (hoop stretch included), p = U′(θ), τ = τ_iso + J p I (small strain: s + p I), and
/// the dilatation stiffness U″(θ) g gᵀ / V₀ added to `k`, g = ∫ J ∇ₓ·N dV₀ (small strain
/// ∫ ∇₀·N dV₀), the divergence taking the hoop column N/r too (the constant-pressure case of
/// the solids' three-field form, Simo, Taylor & Pister 1985).
fn mean_dilatation(
&self,
m: &MaterialModel,
points: &[PlaneKinematics],
small: bool,
committed: &[f64],
updated: &mut [f64],
k: Option<&mut Matrix>,
) -> Result<Vec<Response>> {
let len = m.history_len();
let volume: f64 = points.iter().map(|p| p.dv).sum();
if !(volume > 0.0 && volume.is_finite()) {
return Err(inverted(&format!("2D {}", self.ty.kind.name()), volume));
}
let theta = points.iter().map(|p| p.dv * p.dilatation).sum::<f64>() / volume;
if !(theta > 0.0 && theta.is_finite()) {
return Err(inverted(&format!("2D {}", self.ty.kind.name()), theta));
}
let (pressure, stiffness) = m.volumetric(theta, small).ok_or_else(|| Error::Invalid("volumetric response".into()))?;
let mut out = Vec::with_capacity(points.len());
for (i, p) in points.iter().enumerate() {
let (c, u) = (point_history(committed, len, i), updated.get_mut(i * len..(i + 1) * len).unwrap_or_default());
out.push(if small {
let mut r = m.small_strain(&p.strain, p.heat.temperature, c, u, false)?;
r.stress.iter_mut().take(3).for_each(|s| *s += pressure);
r
} else {
add_pressure(&m.isochoric(&p.heat.mechanical(&p.f), p.heat.temperature, c, u)?, p.j, pressure, 0.0)
});
}
if let Some(k) = k {
let mut g = vec![0.0; k.n];
for p in points {
crate::plane::divergence(&mut g, &p.current, p.dv * p.j);
}
crate::plane::add_outer(k, &g, stiffness / volume);
}
Ok(out)
}
/// Internal forces (u, v per node) and (with `tangent`) the tangent stiffness at nodal
/// displacements `u`, as for [`Solid::finite_strain`].
pub fn finite_strain(&self, m: &MaterialModel, u: &[[f64; 2]], committed: &[f64], updated: &mut [f64], tangent: bool) -> Result<Finite> {
@@ -1016,6 +1102,63 @@ mod tests {
assert!(matches!(stress.finite_strain(&svk, &[[0.0; 2]; 4], &[], &mut [], true), Err(Error::NotSupported(_))));
}
#[test]
fn hybrid_2d_tangents_are_the_derivative_of_the_forces() {
let quad8 = [
[1.0, 0.0, 0.0],
[2.0, 0.1, 0.0],
[2.2, 1.0, 0.0],
[0.9, 1.1, 0.0],
[1.5, 0.0, 0.0],
[2.1, 0.55, 0.0],
[1.5, 1.1, 0.0],
[0.95, 0.5, 0.0],
];
let (shear, bulk) = (300.0, 30000.0);
let neo = MaterialModel::NeoHookean { shear, bulk };
let mr = MaterialModel::Polynomial { name: "Mooney–Rivlin", c: [100.0, 50.0, 0.0, 0.0], bulk };
let hybrid = Formulation::Hybrid { pressures: 1 };
for theory in [Theory::PlaneStrain { thickness: 2.0 }, Theory::Axisymmetric] {
for (kind, x) in [(ElementKind::Quad8, &quad8[..]), (ElementKind::Quad4, &quad8[..4])] {
let plane = Plane::new(kind, x, hybrid, theory).unwrap();
for m in [&neo, &mr] {
let u: Vec<[f64; 2]> = displacement(x.len(), 0.06).iter().map(|v| [v[0], v[1]]).collect();
let k = plane.finite_strain(m, &u, &[], &mut [], true).unwrap().tangent.unwrap();
let scale = k.data.iter().fold(0.0f64, |a, v| a.max(v.abs()));
let h = 1e-6;
for j in 0..2 * x.len() {
let shifted = |s: f64| {
let mut v = u.clone();
v[j / 2][j % 2] += s;
plane.finite_strain(m, &v, &[], &mut [], false).unwrap().force
};
let (p, q) = (shifted(h), shifted(-h));
for i in 0..2 * x.len() {
let numeric = (p[i] - q[i]) / (2.0 * h);
assert!((numeric - k.get(i, j)).abs() < 1e-6 * scale, "{theory:?} {kind:?} {i} {j}: {numeric} vs {}", k.get(i, j));
}
}
}
// At rest the tangent is the linear hybrid stiffness of the same moduli.
let young = 9.0 * bulk * shear / (3.0 * bulk + shear);
let poisson = (3.0 * bulk - 2.0 * shear) / (2.0 * (3.0 * bulk + shear));
let d = isotropic(young, poisson).unwrap();
let k = plane.finite_strain(&neo, &vec![[0.0; 2]; x.len()], &[], &mut [], true).unwrap().tangent.unwrap();
let linear = plane.stiffness(&d).unwrap();
let scale = linear.data.iter().fold(0.0f64, |a, v| a.max(v.abs()));
for (a, b) in k.data.iter().zip(&linear.data) {
assert!((a - b).abs() < 1e-9 * scale, "{a} {b}");
}
}
}
// The linear triangle and plane stress have none; St Venant–Kirchhoff has no split.
assert!(Plane::new(ElementKind::Tri3, &quad8[..3], hybrid, Theory::PlaneStrain { thickness: 1.0 }).is_err());
assert!(Plane::new(ElementKind::Quad4, &quad8[..4], hybrid, Theory::PlaneStress { thickness: 1.0 }).is_err());
let svk = MaterialModel::StVenantKirchhoff(Box::new(isotropic(1000.0, 0.3).unwrap()));
let plane = Plane::new(ElementKind::Quad4, &quad8[..4], hybrid, Theory::Axisymmetric).unwrap();
assert!(matches!(plane.finite_strain(&svk, &[[0.0; 2]; 4], &[], &mut [], true), Err(Error::NotSupported(_))));
}
/// uᵀ K_σ u = ∫ σ_xx (∂u_y/∂x)² dV = σ_xx V for u_y = x under a uniform σ_xx, in a distorted
/// hex20 and a plane strain quad8, and K_σ annihilates rigid translations.
#[test]
+4
View File
@@ -30,6 +30,8 @@
//! - [`face`]: consistent nodal forces of pressure on element faces;
//! - [`contact`]: contact geometry: the closest point of an element face to a point and the
//! bucket grid of the global search;
//! - [`mortar`]: mortar segmentation of a secondary face against a main face and the integration
//! points on the overlap, over [`dual`]'s automatic differentiation for the exact tangent;
//! - [`heat`]: heat conduction (conductivity, capacity, sources, surface flux and convection,
//! heat flux); thermal strain loads and stresses are in [`element`];
//! - [`uniform`]: uniform-strain (one-point) hexahedron and tetrahedron kinematics, hourglass
@@ -59,6 +61,7 @@ pub mod constitutive;
pub mod contact;
pub mod dense;
pub mod dof;
pub mod dual;
pub mod elastoplastic;
pub mod element;
pub mod face;
@@ -68,6 +71,7 @@ pub mod heat;
pub mod hybrid;
pub mod jet;
pub mod material;
pub mod mortar;
pub mod plane;
pub mod plasticity;
pub mod quadrature;
+645
View File
@@ -0,0 +1,645 @@
//! Mortar segmentation and integration: the overlap of a secondary (non-mortar) face with a main
//! (mortar) face, and the integration points on it where both faces' shape functions and
//! positions are known.
//!
//! **Segmentation** (M. A. Puso, T. A. Laursen, *A mortar segment-to-segment contact method for
//! large deformation solid mechanics*, CMAME 193:601–629, 2004, §3; A. Popp, M. W. Gee, W. A.
//! Wall, *A finite deformation mortar contact formulation using a primal–dual active set
//! strategy*, IJNME 79:1354–1391, 2009, §3.3). Both faces are projected along the secondary
//! face's unit normal n onto its plane (through its centroid), and the main polygon is clipped by
//! the secondary one (Sutherland–Hodgman; a quadrilateral whose projection is not convex is
//! split into its two triangles first). Each overlap polygon is split into a fan of triangles
//! integrated with the seven-point degree-5 rule (J. Radon 1948; A. H. Stroud, *Approximate
//! Calculation of Multiple Integrals*, Prentice-Hall 1971, T2:5-1), which integrates the products
//! of two shape functions that the tie and the patch test need exactly on triangles and
//! parallelograms (on a general quadrilateral the inverse of its map is not a polynomial, and the
//! rule is accurate to its degree).
//!
//! **Points.** At an integration point y of the plane, each face's coordinates are found by
//! inverting its projected map: the linear one of a triangle, or the bilinear one of a
//! quadrilateral, x(u, v) = a + b u + c v + d u v, whose inverse is the root in [0, 1] of the
//! quadratic (b × d) u² + (b × c − h × d) u − h × c = 0 (h = y − a, × the scalar cross product of
//! the plane). The projection of a bilinear patch onto a plane is the bilinear patch of its
//! projected corners, so the main face's point found this way is the point of the main surface
//! along n through y, warped or not. The [`Sample`] then holds both faces' shape functions, both
//! points in space, the normal and the weight (the plane's area element times the rule's weight).
//!
//! The kernel is written over [`Real`], so the same code gives the values (`f64`), their
//! gradient ([`crate::dual::Dual`]) or their gradient and Hessian ([`crate::dual::Hyper`]) with
//! respect to the corner coordinates, variables `3 i + k` for secondary corner i and
//! `12 + 3 j + k` for main corner j: the exact linearisation of the segmentation, the normal and
//! the projection, which the consistent tangent of mortar contact needs (Popp et al. 2009, §4).
//!
//! **Edges of 2D models** ([`integrate_edges`]): plane strain, plane stress and axisymmetric
//! models touch along element edges, two-node segments in the XY plane. The main edge is
//! projected along the secondary edge's unit normal onto its line, which maps each main point to
//! one parameter of the secondary edge linearly, so the overlap is an interval of that parameter
//! (B. Yang, T. A. Laursen, X. Meng, *Two dimensional mortar contact methods for large
//! deformation frictional sliding*, IJNME 62:1183–1225, 2005, §3). It is integrated with the
//! three-point Gauss–Legendre rule, exact for the degree-3 products Φ_a N_b r that the
//! axisymmetric patch test needs (the edge's out-of-plane measure, the thickness or 2π r at the
//! secondary point, is part of the weight). Points stay three-component with z = 0, so the solver
//! takes edges through the same variables as faces.
use crate::dual::Real;
use fieldcraft_model::Extent;
/// A point in space over a scalar.
pub type Point<T> = [T; 3];
/// A point of the secondary face's plane.
type Flat<T> = [T; 2];
/// Radon's seven-point rule on a triangle, exact for degree 5: barycentric coordinates of the
/// second and third corners and weights summing to one.
fn rule() -> [([f64; 2], f64); 7] {
let s = 15f64.sqrt();
let (a, b) = ((6.0 - s) / 21.0, (9.0 + 2.0 * s) / 21.0);
let (c, d) = ((6.0 + s) / 21.0, (9.0 - 2.0 * s) / 21.0);
let (wa, wc) = ((155.0 - s) / 1200.0, (155.0 + s) / 1200.0);
[([1.0 / 3.0, 1.0 / 3.0], 0.225), ([a, a], wa), ([b, a], wa), ([a, b], wa), ([c, c], wc), ([d, c], wc), ([c, d], wc)]
}
/// One integration point of a segment.
#[derive(Debug, Clone, Copy)]
pub struct Sample<T> {
/// The rule's weight times the plane's area element (the secondary face's projected area).
pub weight: T,
/// The secondary face's shape functions at the point (0 past its corners).
pub secondary: [T; 4],
/// The main face's shape functions at the point.
pub main: [T; 4],
/// The point on the secondary face, and on the main face along the normal.
pub xs: Point<T>,
pub xm: Point<T>,
/// The secondary face's unit normal (outward from its element).
pub normal: Point<T>,
}
impl<T: Real> Sample<T> {
/// The gap along the secondary normal, (x_m − x_s) · n: positive where the faces are apart.
pub fn gap(&self) -> T {
dot(sub(self.xm, self.xs), self.normal)
}
}
fn sub<T: Real>(a: Point<T>, b: Point<T>) -> Point<T> {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn dot<T: Real>(a: Point<T>, b: Point<T>) -> T {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross<T: Real>(a: Point<T>, b: Point<T>) -> Point<T> {
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
}
fn scale<T: Real>(a: Point<T>, s: T) -> Point<T> {
[a[0] * s, a[1] * s, a[2] * s]
}
fn cross2<T: Real>(a: Flat<T>, b: Flat<T>) -> T {
a[0] * b[1] - a[1] * b[0]
}
fn sub2<T: Real>(a: Flat<T>, b: Flat<T>) -> Flat<T> {
[a[0] - b[0], a[1] - b[1]]
}
/// A face's area vector: its outward normal times its area (flat triangle; for a bilinear
/// quadrilateral half the cross product of its diagonals, the area of its projection on the
/// plane normal to it).
pub fn area_vector<T: Real>(x: &[Point<T>]) -> Option<Point<T>> {
let half = |v: Point<T>| scale(v, T::cst(0.5));
match x {
[a, b, c] => Some(half(cross(sub(*b, *a), sub(*c, *a)))),
[a, b, c, d] => Some(half(cross(sub(*c, *a), sub(*d, *b)))),
_ => None,
}
}
/// A projected face as convex counter-clockwise pieces for the clipping: itself when it is
/// convex (no artificial diagonal, whose crossings with the other face's edges would change the
/// overlap's polygons, and the integration's round-off, as the faces move), else its two
/// triangles.
fn pieces<T: Real>(points: &[Flat<T>]) -> Vec<Vec<Flat<T>>> {
let mut whole = points.to_vec();
if signed_area(&whole).val() < 0.0 {
whole.reverse();
}
let n = whole.len();
let convex = (0..n).all(|i| {
let (a, b, c) = (whole[i], whole[(i + 1) % n], whole[(i + 2) % n]);
cross2(sub2(b, a), sub2(c, b)).val() > 0.0
});
if convex || n == 3 {
return vec![whole];
}
[[0, 1, 2], [0, 2, 3]].iter().map(|t| counter_clockwise(t, points)).collect()
}
fn signed_area<T: Real>(p: &[Flat<T>]) -> T {
let mut s = T::cst(0.0);
for (i, a) in p.iter().enumerate() {
let b = p.get((i + 1) % p.len()).copied().unwrap_or(*a);
s = s + cross2(*a, b);
}
s * 0.5
}
/// The corners `t` of `points`, counter-clockwise.
fn counter_clockwise<T: Real>(t: &[usize; 3], points: &[Flat<T>]) -> Vec<Flat<T>> {
let mut out: Vec<Flat<T>> = t.iter().filter_map(|i| points.get(*i).copied()).collect();
if signed_area(&out).val() < 0.0 {
out.reverse();
}
out
}
/// A vertex this close to a clip edge, relative to the edge's length, is on it.
const ON_EDGE: f64 = 1e-8;
/// `subject` clipped by the convex counter-clockwise polygon `clip` (Sutherland–Hodgman), the
/// sides decided on the values. A vertex within [`ON_EDGE`] of a clip edge's line counts as on
/// it (kept, and never cut): the intersection of two nearly coincident edges is ill-conditioned,
/// its position and above all its derivatives swamped by round-off, while the vertex itself is
/// as good a corner of the overlap to that precision. Edges are cut only between a vertex
/// clearly inside and one clearly outside, where the intersection is well conditioned.
fn clip<T: Real>(subject: &[Flat<T>], clip: &[Flat<T>]) -> Vec<Flat<T>> {
let mut out: Vec<Flat<T>> = subject.to_vec();
for (i, a) in clip.iter().enumerate() {
let Some(b) = clip.get((i + 1) % clip.len()).copied() else { break };
let input = std::mem::take(&mut out);
let edge = sub2(b, *a);
let eps = ON_EDGE * (edge[0].val() * edge[0].val() + edge[1].val() * edge[1].val());
let side = |p: Flat<T>| cross2(edge, sub2(p, *a));
for (j, p) in input.iter().enumerate() {
let Some(q) = input.get((j + 1) % input.len()).copied() else { break };
let (sp, sq) = (side(*p), side(q));
if sp.val() >= -eps {
out.push(*p);
}
if (sp.val() > eps && sq.val() < -eps) || (sp.val() < -eps && sq.val() > eps) {
let t = sp / (sp - sq);
out.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
}
}
if out.is_empty() {
break;
}
}
out
}
/// The shape functions of a face (of 3 or 4 projected corners `p`) at plane point `y`: the
/// inverse of its linear or bilinear map. `None` when it has no inverse there.
fn shape_at<T: Real>(p: &[Flat<T>], y: Flat<T>) -> Option<[T; 4]> {
let zero = T::cst(0.0);
match p {
[p0, p1, p2] => {
let (e1, e2, h) = (sub2(*p1, *p0), sub2(*p2, *p0), sub2(y, *p0));
let det = cross2(e1, e2);
if !(det.val().abs() > 0.0) {
return None;
}
let v = cross2(h, e2) / det;
let w = cross2(e1, h) / det;
Some([T::cst(1.0) - v - w, v, w, zero])
}
[p0, p1, p2, p3] => {
let b = sub2(*p1, *p0);
let c = sub2(*p3, *p0);
let d = [p0[0] - p1[0] + p2[0] - p3[0], p0[1] - p1[1] + p2[1] - p3[1]];
let h = sub2(y, *p0);
let k2 = cross2(b, d);
let k1 = cross2(b, c) - cross2(h, d);
let k0 = -cross2(h, c);
let u = if k2.val().abs() <= 1e-12 * k1.val().abs() {
if !(k1.val().abs() > 0.0) {
return None;
}
-k0 / k1
} else {
// The roots of k2 u² + k1 u + k0, computed without cancellation; the one in [0, 1]
// (the nearer when round-off puts both outside).
let disc = k1 * k1 - k2 * k0 * 4.0;
let root = if disc.val() > 0.0 { disc.sqrt() } else { T::cst(0.0) };
let q = if k1.val() >= 0.0 { -(k1 + root) * 0.5 } else { (root - k1) * 0.5 };
let mut candidates = [None, None];
if q.val().abs() > 0.0 {
candidates[0] = Some(q / k2);
candidates[1] = Some(k0 / q);
} else {
candidates[0] = Some(-k1 / (k2 * 2.0));
}
let distance = |u: f64| {
if u < 0.0 {
-u
} else if u > 1.0 {
u - 1.0
} else {
0.0
}
};
candidates.into_iter().flatten().filter(|u| u.val().is_finite()).min_by(|a, b| distance(a.val()).total_cmp(&distance(b.val())))?
};
// v from the better conditioned component of h − u b = v (c + d u).
let m = [c[0] + d[0] * u, c[1] + d[1] * u];
let k = if m[0].val().abs() >= m[1].val().abs() { 0 } else { 1 };
if !(m[k].val().abs() > 0.0) {
return None;
}
let v = (h[k] - b[k] * u) / m[k];
let (s, t) = (u * 2.0 - 1.0, v * 2.0 - 1.0);
let one = T::cst(1.0);
Some([(one - s) * (one - t) * 0.25, (one + s) * (one - t) * 0.25, (one + s) * (one + t) * 0.25, (one - s) * (one + t) * 0.25])
}
_ => None,
}
}
fn interpolate<T: Real>(x: &[Point<T>], n: &[T; 4]) -> Point<T> {
let mut out = [T::cst(0.0); 3];
for (xi, ni) in x.iter().zip(n) {
for k in 0..3 {
out[k] = out[k] + xi[k] * *ni;
}
}
out
}
/// Integrate over the overlap of secondary face `secondary` with main face `main` (3 or 4
/// corners each, in their faces' node order): `f` is called at every integration point. `None`
/// when a face has another number of corners or the secondary face has no normal (collapsed);
/// faces that do not overlap give no point.
pub fn integrate<T: Real>(secondary: &[Point<T>], main: &[Point<T>], mut f: impl FnMut(&Sample<T>)) -> Option<()> {
if !matches!(main.len(), 3 | 4) {
return None;
}
let area = area_vector(secondary)?;
let length = dot(area, area).sqrt();
if !(length.val() > 0.0 && length.val().is_finite()) {
return None;
}
let normal = scale(area, T::cst(1.0) / length);
let count = T::cst(secondary.len() as f64);
let mut center = [T::cst(0.0); 3];
for x in secondary {
for k in 0..3 {
center[k] = center[k] + x[k] / count;
}
}
// A basis of the plane, (e1, e2, n) right-handed, e1 towards the first corner.
let r = sub(*secondary.first()?, center);
let r = sub(r, scale(normal, dot(r, normal)));
let rl = dot(r, r).sqrt();
if !(rl.val() > 0.0) {
return None;
}
let e1 = scale(r, T::cst(1.0) / rl);
let e2 = cross(normal, e1);
let flat = |x: &Point<T>| -> Flat<T> {
let d = sub(*x, center);
[dot(d, e1), dot(d, e2)]
};
let own: Vec<Flat<T>> = secondary.iter().map(flat).collect();
let theirs: Vec<Flat<T>> = main.iter().map(flat).collect();
let rule = rule();
let (own_pieces, their_pieces) = (pieces(&own), pieces(&theirs));
for s in &own_pieces {
for m in &their_pieces {
let overlap = clip(m, s);
let Some(o) = overlap.first().copied() else { continue };
for w in overlap.windows(2).skip(1) {
let (p, q) = (w[0], w[1]);
let doubled = cross2(sub2(p, o), sub2(q, o));
if !(doubled.val() > 0.0) {
continue;
}
for (bary, weight) in rule {
let y = [0, 1].map(|k| o[k] + (p[k] - o[k]) * bary[0] + (q[k] - o[k]) * bary[1]);
let (Some(ns), Some(nm)) = (shape_at(&own, y), shape_at(&theirs, y)) else { continue };
f(&Sample {
weight: doubled * (0.5 * weight),
secondary: ns,
main: nm,
xs: interpolate(secondary, &ns),
xm: interpolate(main, &nm),
normal,
});
}
}
}
}
Some(())
}
/// The out-of-plane measure of a 2D model at a point: the thickness, or 2π x.
fn measure<T: Real>(extent: Extent, x: T) -> T {
match extent {
Extent::Thickness(t) => T::cst(t),
Extent::Revolved => x * (2.0 * std::f64::consts::PI),
}
}
/// The unit tangent of a two-point edge in the XY plane and its length.
fn edge_frame<T: Real>(x: &[Point<T>]) -> Option<(Flat<T>, T)> {
let [a, b] = x else { return None };
let t = [b[0] - a[0], b[1] - a[1]];
let length = (t[0] * t[0] + t[1] * t[1]).sqrt();
if !(length.val() > 0.0 && length.val().is_finite()) {
return None;
}
let inv = T::cst(1.0) / length;
Some(([t[0] * inv, t[1] * inv], length))
}
/// An edge's area vector in a 2D model (two corners in the XY plane): its unit normal
/// (t_y, −t_x), outward when the edge runs counter-clockwise round its element, times its
/// length and its out-of-plane measure at its midpoint (∫ 2π r ds exactly for a straight edge).
pub fn edge_area_vector<T: Real>(x: &[Point<T>], extent: Extent) -> Option<Point<T>> {
let (t, length) = edge_frame(x)?;
let [a, b] = x else { return None };
let size = length * measure(extent, (a[0] + b[0]) * 0.5);
Some([t[1] * size, -(t[0] * size), T::cst(0.0)])
}
/// Integrate over the overlap of secondary edge `secondary` with main edge `main` of a 2D model
/// (two corners each, z ignored), as [`integrate`] does for faces: the samples' shape functions
/// are those of the edges' two corners (the last two are zero), the normal is the secondary
/// edge's (t_y, −t_x, 0) and the weight carries the out-of-plane measure `extent` at the
/// secondary point. `None` when an edge does not have two corners or the secondary one has no
/// length; edges that do not overlap, or a main edge along the normal, give no point.
pub fn integrate_edges<T: Real>(secondary: &[Point<T>], main: &[Point<T>], extent: Extent, mut f: impl FnMut(&Sample<T>)) -> Option<()> {
let (t, length) = edge_frame(secondary)?;
let ([s0, s1], [m0, m1]) = (secondary, main) else { return None };
let inv = T::cst(1.0) / length;
let along = |p: &Point<T>| ((p[0] - s0[0]) * t[0] + (p[1] - s0[1]) * t[1]) * inv;
let (a, b) = (along(m0), along(m1));
let span = b - a;
if !(span.val().abs() > 1e-12) || !span.val().is_finite() {
return Some(());
}
let zero = T::cst(0.0);
let one = T::cst(1.0);
let (low, high) = if a.val() <= b.val() { (a, b) } else { (b, a) };
let lo = if low.val() > 0.0 { low } else { zero };
let hi = if high.val() < 1.0 { high } else { one };
let width = hi - lo;
if !(width.val() > 0.0) {
return Some(());
}
let normal = [t[1], -t[0], zero];
let size = width * length;
// Three-point Gauss–Legendre mapped from [−1, 1] onto the overlap.
for &(g, w) in crate::quadrature::gauss_legendre(3) {
let xi = lo + width * (0.5 * (1.0 + g));
let eta = (xi - a) / span;
let xs = [s0[0] + (s1[0] - s0[0]) * xi, s0[1] + (s1[1] - s0[1]) * xi, zero];
let xm = [m0[0] + (m1[0] - m0[0]) * eta, m0[1] + (m1[1] - m0[1]) * eta, zero];
f(&Sample {
weight: size * measure(extent, xs[0]) * (0.5 * w),
secondary: [one - xi, xi, zero, zero],
main: [one - eta, eta, zero, zero],
xs,
xm,
normal,
});
}
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dual::{Dual, Hyper, VARS};
fn square(x0: f64, y0: f64, side: f64, z: f64, up: bool) -> Vec<[f64; 3]> {
let c = [[x0, y0, z], [x0 + side, y0, z], [x0 + side, y0 + side, z], [x0, y0 + side, z]];
if up { c.to_vec() } else { vec![c[0], c[3], c[2], c[1]] }
}
/// ∫ N_a over the overlap and ∫ N_a g, per secondary corner.
fn integrals(s: &[[f64; 3]], m: &[[f64; 3]]) -> ([f64; 4], [f64; 4], f64) {
let (mut d, mut g, mut area) = ([0.0; 4], [0.0; 4], 0.0);
integrate(s, m, |p| {
area += p.weight;
for a in 0..4 {
d[a] += p.weight * p.secondary[a];
g[a] += p.weight * p.secondary[a] * p.gap();
}
})
.unwrap();
(d, g, area)
}
#[test]
fn a_covered_face_integrates_its_shape_functions_and_gap() {
// Secondary face up (normal +z), main face facing it 0.1 above.
let s = square(0.0, 0.0, 1.0, 0.0, true);
let m = square(-0.5, -0.5, 2.0, 0.1, false);
let (d, g, area) = integrals(&s, &m);
assert!((area - 1.0).abs() < 1e-14);
for a in 0..4 {
assert!((d[a] - 0.25).abs() < 1e-14 && (g[a] - 0.025).abs() < 1e-14, "{d:?} {g:?}");
}
// Half covered: the overlap is the strip x > 0.5.
let (d, _, area) = integrals(&s, &square(0.5, -0.5, 2.0, 0.1, false));
assert!((area - 0.5).abs() < 1e-14);
assert!((d[0] - 0.0625).abs() < 1e-14 && (d[1] - 0.1875).abs() < 1e-14, "{d:?}");
// Apart: nothing.
let (_, _, area) = integrals(&s, &square(3.0, 0.0, 1.0, 0.1, false));
assert_eq!(area, 0.0);
}
/// The sums over a 3 × 3 grid of main faces (triangles in one corner) under secondary face
/// `s`, against a tensor-product Gauss rule on the face itself.
fn covered(s: &[[f64; 3]; 4]) -> ([f64; 4], [f64; 4], f64, f64) {
let mut d = [0.0; 4];
let mut area = 0.0;
for i in 0..3 {
for j in 0..3 {
let quad = square(-0.3 + 0.6 * i as f64, -0.3 + 0.6 * j as f64, 0.6, 0.2, false);
let faces: Vec<Vec<[f64; 3]>> =
if i == 0 && j == 0 { vec![vec![quad[0], quad[1], quad[2]], vec![quad[0], quad[2], quad[3]]] } else { vec![quad] };
for f in faces {
let (da, _, a) = integrals(s, &f);
area += a;
for k in 0..4 {
d[k] += da[k];
}
}
}
}
let mut reference = [0.0; 4];
let mut exact = 0.0;
let g = [-(0.6f64).sqrt(), 0.0, 0.6f64.sqrt()];
let w = [5.0 / 9.0, 8.0 / 9.0, 5.0 / 9.0];
for (a, wa) in g.iter().zip(w) {
for (b, wb) in g.iter().zip(w) {
let n = [(1.0 - a) * (1.0 - b), (1.0 + a) * (1.0 - b), (1.0 + a) * (1.0 + b), (1.0 - a) * (1.0 + b)].map(|v| v / 4.0);
let dxa: [f64; 3] =
std::array::from_fn(|k| 0.25 * (-(1.0 - b) * s[0][k] + (1.0 - b) * s[1][k] + (1.0 + b) * s[2][k] - (1.0 + b) * s[3][k]));
let dxb: [f64; 3] =
std::array::from_fn(|k| 0.25 * (-(1.0 - a) * s[0][k] - (1.0 + a) * s[1][k] + (1.0 + a) * s[2][k] + (1.0 - a) * s[3][k]));
let j = crate::frame::norm(crate::frame::cross(dxa, dxb));
exact += wa * wb * j;
for k in 0..4 {
reference[k] += wa * wb * j * n[k];
}
}
}
(d, reference, area, exact)
}
#[test]
fn non_matching_main_faces_add_up_to_the_covered_integrals() {
// A parallelogram: its shape functions are polynomials of the plane, integrated exactly.
let (d, reference, area, exact) = covered(&[[0.0, 0.0, 0.0], [1.0, 0.2, 0.0], [1.1, 1.1, 0.0], [0.1, 0.9, 0.0]]);
assert!((area - exact).abs() < 1e-13, "{area} {exact}");
for k in 0..4 {
assert!((d[k] - reference[k]).abs() < 1e-13, "{d:?} {reference:?}");
}
// A general quadrilateral: its inverse map is not polynomial; the rule is accurate to
// its degree.
let (d, reference, area, exact) = covered(&[[0.0, 0.0, 0.0], [1.1, 0.1, 0.0], [1.0, 0.9, 0.0], [0.05, 1.2, 0.0]]);
assert!((area - exact).abs() < 1e-13, "{area} {exact}");
for k in 0..4 {
assert!((d[k] - reference[k]).abs() < 1e-5 * reference[k], "{d:?} {reference:?}");
}
}
/// ∫ N_a g over a warped, tilted pair, as a function of all 24 coordinates.
fn weighted_gap<T: Real>(x: &[T; VARS], a: usize) -> T {
let s: Vec<Point<T>> = (0..4).map(|i| [x[3 * i], x[3 * i + 1], x[3 * i + 2]]).collect();
let m: Vec<Point<T>> = (0..4).map(|j| [x[12 + 3 * j], x[13 + 3 * j], x[14 + 3 * j]]).collect();
let mut g = T::cst(0.0);
integrate(&s, &m, |p| g = g + p.weight * p.secondary[a] * p.gap()).unwrap();
g
}
#[test]
fn the_automatic_derivatives_are_those_of_the_integral() {
let base: [f64; VARS] = [
0.0, 0.0, 0.0, 1.0, 0.05, 0.02, 1.1, 0.9, -0.03, -0.05, 1.0, 0.01, // secondary
-0.2, -0.3, 0.12, -0.25, 1.15, 0.08, 1.2, 1.1, 0.1, 0.9, -0.2, 0.15, // main, facing down
];
let a = 2;
let duals: [Dual; VARS] = std::array::from_fn(|k| Dual::var(base[k], k));
let hypers: [Hyper; VARS] = std::array::from_fn(|k| Hyper::var(base[k], k));
let d = weighted_gap(&duals, a);
let e = weighted_gap(&hypers, a);
let v = weighted_gap(&base, a);
assert!((d.v - v).abs() < 1e-14 && (e.v - v).abs() < 1e-14);
let h = 1e-6;
let shifted = |k: usize, by: f64| {
let mut x = base;
x[k] += by;
x
};
for k in 0..VARS {
let fd = (weighted_gap(&shifted(k, h), a) - weighted_gap(&shifted(k, -h), a)) / (2.0 * h);
assert!((d.g[k] - fd).abs() < 1e-7 && (e.g[k] - d.g[k]).abs() < 1e-13, "gradient {k}: {} {fd}", d.g[k]);
// The Hessian's row k against differences of the gradient.
let (plus, minus) = (shifted(k, h), shifted(k, -h));
let gp = weighted_gap(&std::array::from_fn::<Dual, VARS, _>(|i| Dual::var(plus[i], i)), a);
let gm = weighted_gap(&std::array::from_fn::<Dual, VARS, _>(|i| Dual::var(minus[i], i)), a);
for j in 0..VARS {
let fd = (gp.g[j] - gm.g[j]) / (2.0 * h);
assert!((e.hessian(k, j) - fd).abs() < 1e-6, "hessian ({k}, {j}): {} {fd}", e.hessian(k, j));
}
}
// A rigid translation changes nothing: the gradient sums to zero per direction.
for c in 0..3 {
let sum: f64 = (0..8).map(|n| d.g[3 * n + c]).sum();
assert!(sum.abs() < 1e-13, "{sum}");
}
}
#[test]
fn edges_integrate_their_overlap_and_measure() {
// Secondary edge along +x at y = 0 (normal −y), main edge 0.1 below, half overlapping.
let s = [[1.0, 0.0, 0.0], [2.0, 0.0, 0.0]];
let m = [[2.5, -0.1, 0.0], [1.5, -0.1, 0.0]];
for (extent, at) in [(Extent::Thickness(3.0), (3.0, 0.0)), (Extent::Revolved, (0.0, 2.0 * std::f64::consts::PI))] {
let at = |x: f64| at.0 + at.1 * x;
let (mut d, mut g, mut area) = ([0.0; 2], 0.0, 0.0);
integrate_edges(&s, &m, extent, |p| {
area += p.weight;
g += p.weight * p.gap();
for a in 0..2 {
d[a] += p.weight * p.secondary[a];
}
assert!((p.xm[1] + 0.1).abs() < 1e-15 && (p.xm[0] - p.xs[0]).abs() < 1e-15);
})
.unwrap();
// ∫_{1.5}^{2} m(x) dx and ∫ (x − 1) m(x) dx (the second corner's share).
let simpson = |f: &dyn Fn(f64) -> f64| (f(1.5) + 4.0 * f(1.75) + f(2.0)) * 0.5 / 6.0;
assert!((area - simpson(&|x| at(x))).abs() < 1e-12, "{area}");
assert!((d[1] - simpson(&|x| (x - 1.0) * at(x))).abs() < 1e-12);
assert!((g - 0.1 * area).abs() < 1e-12);
}
// The area vector points along −y with the edge's measure.
let v = edge_area_vector(&s, Extent::Revolved).unwrap();
assert!(v[0].abs() < 1e-15 && (v[1] + 2.0 * std::f64::consts::PI * 1.5).abs() < 1e-12);
// Apart, perpendicular or degenerate: nothing.
let mut count = 0;
integrate_edges(&s, &[[3.0, -0.1, 0.0], [4.0, -0.1, 0.0]], Extent::Revolved, |_| count += 1).unwrap();
integrate_edges(&s, &[[1.5, -0.1, 0.0], [1.5, -1.0, 0.0]], Extent::Revolved, |_| count += 1).unwrap();
assert_eq!(count, 0);
assert!(integrate_edges(&[[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]], &m, Extent::Revolved, |_| {}).is_none());
}
#[test]
fn edge_derivatives_are_those_of_the_integral() {
let base: [f64; VARS] = std::array::from_fn(|k| match k {
0 => 1.0,
1 => 0.02,
3 => 2.1,
4 => -0.05,
12 => 2.4,
13 => -0.12,
15 => 1.3,
16 => -0.08,
_ => 0.0,
});
let gap = |x: &[Hyper; VARS]| {
let s = [[x[0], x[1], x[2]], [x[3], x[4], x[5]]];
let m = [[x[12], x[13], x[14]], [x[15], x[16], x[17]]];
let mut g = Hyper::cst(0.0);
integrate_edges(&s, &m, Extent::Revolved, |p| g = g + p.weight * p.secondary[1] * p.gap()).unwrap();
g
};
let value = |x: [f64; VARS]| gap(&std::array::from_fn(|k| Hyper::cst(x[k]))).v;
let e = gap(&std::array::from_fn(|k| Hyper::var(base[k], k)));
let h = 1e-6;
for k in [0, 1, 3, 4, 12, 13, 15, 16] {
let (mut p, mut m) = (base, base);
p[k] += h;
m[k] -= h;
let fd = (value(p) - value(m)) / (2.0 * h);
assert!((e.g[k] - fd).abs() < 1e-7, "gradient {k}: {} {fd}", e.g[k]);
for j in [0, 1, 3, 4, 12, 13, 15, 16] {
let (mut pp, mut pm, mut mp, mut mm) = (p, p, m, m);
pp[j] += h;
pm[j] -= h;
mp[j] += h;
mm[j] -= h;
let fd = (value(pp) - value(pm) - value(mp) + value(mm)) / (4.0 * h * h);
assert!((e.hessian(k, j) - fd).abs() < 2e-3, "hessian ({k}, {j}): {} {fd}", e.hessian(k, j));
}
}
}
#[test]
fn degenerate_faces_give_nothing() {
let s = square(0.0, 0.0, 1.0, 0.0, true);
let collapsed = [[0.0; 3], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]];
assert!(integrate(&collapsed, &s, |_| {}).is_none());
assert!(integrate(&s, &s[..2], |_| {}).is_none());
let mut count = 0;
integrate(&s, &[[f64::NAN, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], |_| count += 1);
assert_eq!(count, 0);
}
}
Loaded 100 of 269 files, more files were not shown because too many files have changed in this diff. Show more