diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8e218d0..8005ddc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -5,7 +5,8 @@ # docker - the same suite inside the pinned python:3.13-slim image, which is # the deploy path. It is the only place that catches a broken # version pin from requirements.txt or a new source file missing -# from the Dockerfile's explicit COPY list (see AGENTS.md). +# from the Dockerfile's explicit COPY list (see AGENTS.md). It then +# builds the runtime stage and checks that the app comes up. # # No apt step in the pytest job: none of the runtime wheels link against libGL # or libglib, the Dockerfile installs those only because python:3.13-slim ships @@ -63,3 +64,21 @@ jobs: # The test stage runs pytest during the build: a red test fails the build. - name: Build test stage run: docker build --target test . + + # The runtime stage is what compose deploys. It copies its files one by + # one, so a module missing there only showed up at deploy time. + - name: Build runtime stage + run: docker build --target runtime -t inlayer:ci . + + # Imports catch a missing module; the health check that the app really + # comes up as appuser (useradd, permissions, CMD). + - name: Smoke-test the runtime image + run: | + docker run --rm inlayer:ci python -c "import app_helpers, inlayer, i18n" + docker run -d --name inlayer-smoke -p 8501:8501 inlayer:ci + for i in $(seq 1 30); do + curl -fsS http://localhost:8501/_stcore/health && exit 0 + sleep 2 + done + docker logs inlayer-smoke + exit 1 diff --git a/AGENTS.md b/AGENTS.md index 85fb948..e93613c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,12 +16,13 @@ High-signal context for OpenCode sessions in this repo. ## Testing -- A `pytest` suite lives in `tests/` (config validation, each pipeline step, `app_helpers`, end-to-end, CLI). Run with `pytest` (full suite ~10 s) or `pytest -m "not slow"` to skip subprocess/CLI tests. +- A `pytest` suite lives in `tests/` (config validation, each pipeline step, `app_helpers`, end-to-end, CLI). Run with `pytest` (full suite ~70 s) or `pytest -m "not slow"` to skip subprocess/CLI tests and the finest-pitch geometry runs. - **Never test a re-implementation of shipped code.** If a helper is hard to import, move it somewhere importable (see `app_helpers.py`) instead of copying its body into the test file — a copied test passes even when the real function is broken. - **After every code change, run the tests.** If the suite fails, fix the regression before considering the change done. - **Extend the suite when you add or modify behavior.** New functions, new branches, new edge cases or bug fixes must come with matching tests. Keep test docstrings and comments in English per the language convention below. - Shared fixtures (cube/sphere STL, fast config) live in `tests/conftest.py` — reuse them instead of regenerating geometry. -- **CI is `.github/workflows/tests.yml`** (pull requests and pushes to `main`): one job runs `pytest` on a plain runner with Python 3.13, a second builds `docker build --target test .`. The Docker job is not redundant — it is what catches a version pin that no longer resolves on `python:3.13-slim` and a new source file missing from the Dockerfile's explicit `COPY` list. Its very first run proved the point: `.streamlit/` and the `Dockerfile` were missing from the `test` stage, so `docker build --target test .` had been failing four tests in `test_streamlit_config.py` while the same suite was green locally. Adding a source file therefore means touching the Dockerfile in the same change, or CI goes red. The pytest job deliberately installs no apt packages: no runtime wheel links against libGL or libglib (checked with `ldd`), the Dockerfile needs them only because the slim image ships with almost nothing. +- **Geometry changes are tested by measuring the output mesh, not by re-checking a formula.** `tests/geometry_probe.py` measures a finished inlay independently of the pipeline (pocket bounds against the box, `min_gap` between pockets, ray casts, shell count); `tests/test_geometry_invariants.py` pins the invariants with it (walls = `wall_thickness`, wall between cavities = `figure_gap`, every figure has its own pocket, no sealed void, no recess breakthrough). The old suite asserted `h == wall + df * ...` and stayed green through every one of those bugs. +- **CI is `.github/workflows/tests.yml`** (pull requests and pushes to `main`): one job runs `pytest` on a plain runner with Python 3.13, a second builds `docker build --target test .` and then the `runtime` stage with a smoke test (imports + `/_stcore/health`). `tests/test_streamlit_config.py` also checks statically that the runtime stage copies `app.py`, every repo module it imports and `.streamlit/` - stage by stage, because a whole-file search was satisfied by the test stage alone. The Docker job is not redundant — it is what catches a version pin that no longer resolves on `python:3.13-slim` and a new source file missing from the Dockerfile's explicit `COPY` list. Its very first run proved the point: `.streamlit/` and the `Dockerfile` were missing from the `test` stage, so `docker build --target test .` had been failing four tests in `test_streamlit_config.py` while the same suite was green locally. Adding a source file therefore means touching the Dockerfile in the same change, or CI goes red. The pytest job deliberately installs no apt packages: no runtime wheel links against libGL or libglib (checked with `ldd`), the Dockerfile needs them only because the slim image ships with almost nothing. ## Language convention @@ -37,21 +38,27 @@ High-signal context for OpenCode sessions in this repo. ## Architecture -- `inlayer.py` is the pipeline library module. It exposes a frozen `Config` dataclass plus pipeline functions (`apply_euler_rotation`, `prepare_figure`, `dilate`, `arrange_figures`, `build_inlay`, `wall_thickness_stats_3d`). All parameters flow through `Config`. -- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`, `quantize_axis_value`, `load_preview_mesh`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) +- `inlayer.py` is the pipeline library module. It exposes a frozen `Config` dataclass plus pipeline functions (`apply_euler_rotation`, `prepare_figure`, `dilate`, `build_inlay`, `wall_thickness_stats_3d`; `arrange_footprints` is the layout `build_inlay` uses). All parameters flow through `Config`. +- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.) - `app.py` is a Streamlit frontend. It builds an `inlayer.Config` from the sidebar widgets and passes it into the pipeline functions (no global mutation). -- `i18n.py` holds the **bilingual UI** (English/German). `t(key, **kwargs)` looks up `TRANSLATIONS` and fills named placeholders; unknown keys return the key itself rather than raising, so a missing string can never abort a running computation. Keys are namespaced `app.*` / `cli.*` / `pipeline.*` / `config.*` / `error.*`. +- `i18n.py` holds the **bilingual UI** (English/German). `t(key, **kwargs)` looks up `TRANSLATIONS` and fills named placeholders; unknown keys return the key itself rather than raising, so a missing string can never abort a running computation. Keys are namespaced `app.*` / `cli.*` / `pipeline.*` / `config.*` / `error.*` / `check.*` (wall-check findings, shared by CLI and app through `inlayer.describe_violation`). - **The current language is a `ContextVar`, not a module global.** Streamlit runs each session's script in its own thread; a shared global would let one session's language selection bleed into another's. Do not "simplify" this into a plain variable. - **`ThreadPoolExecutor` workers do not inherit ContextVars.** `_parallel_map` captures the language before submitting and re-applies it inside each worker — without that, parallel steps log in the default language. `tests/test_i18n.py` pins this behaviour *and* the assumption behind it. Any new thread pool that logs needs the same treatment. - **In `inlayer.py` the translation function is imported as `t_`, not `t`.** `t` is used throughout the module as the timestamp returned by `_log()`; importing the translator under that name shadows it and fails at runtime with `'float' object is not callable`. -- **`app.py`'s "all figures" sentinel stays untranslated.** `ALL_FIGURES` is a stored session-state value, not display text — translating it would invalidate the saved selection on a language switch. It is rendered through `format_func` (`_fig_label`) instead. The same applies to any option value that is persisted rather than merely shown. +- **`app.py`'s "all figures" sentinel stays untranslated.** `ALL_FIGURES` is a stored session-state value, not display text — translating it would invalidate the saved selection on a language switch. It is rendered through `format_func` (`_fig_label`) instead. The same applies to any option value that is persisted rather than merely shown - the figure options are upload ids for the same reason. +- **Every widget in `app.py` has a fixed, language-independent `key`.** Streamlit derives an unkeyed widget's identity from its label, which is translated: a language switch created new widgets, the uploads vanished and every setting fell back to its default. `tests/test_app_render.py` fails on a widget call without `key=`. +- **Per-figure settings belong to an upload (`UploadedFile.file_id`), not to a file name.** `fig_offsets_dict` is keyed by id; entries of removed uploads are deleted (re-uploading starts from the defaults), duplicate names are shown as `model.stl (2)` (`figure_labels`). Two different `model.stl` files used to share one entry and moved together. +- **Selections and sliders are reconciled with the uploads before any widget exists.** All three per-figure controls (recess position, offsets, rotation) resolve their selection through `app_helpers.resolve_selection` and reload their widgets from the stored values whenever the figure they show changes - including a removed upload, a new first figure under "all figures" and widget state dropped while hidden. Don't go back to loading in the selectbox `on_change` only: that missed every change to the file list, and the sliders then showed values the pipeline did not use. +- **`app_helpers.applied_figure_params` is the only source of per-figure values.** The run, the instant preview and the staleness snapshot all read it - never a slider, which only shows the selected figure (reading the slider made a mere selection change look like a settings change). - **New user-facing text needs both languages.** `tests/test_i18n.py` fails on a missing translation, on placeholders that differ between languages, on positional `{}` placeholders, and on keys referenced in source but absent from the table. -- **Finger recesses** (`Config.enable_finger_recesses`, `Config.finger_radius`) are exposed in the Web-App and via the CLI flags `--finger-recesses` / `--finger-radius`. `build_inlay` communicates results back through `inlay.metadata`: `violating_indices` (figures violating min wall thickness) and `finger_recesses` (recess meshes for the preview). -- **Two different knobs move the recesses.** `finger_recess_z_offset` (mm) sinks them below the box's top edge; `finger_recess_position` (`-1.0` … `1.0`) slides the pair *along* the figure, across `finger_recess_axis`, to pick the grip point. The latter is relative to the figure's usable half length (half extent minus `finger_radius`), not mm: one setting then fits figures of different sizes and `±1.0` can never push a hemisphere past the figure's own footprint into a box wall — the box is only padded by `finger_radius` along the recess axis, not across it. The silhouette search band is centred on that grip position, so the recesses hug the figure where the fingers actually reach in. **The grip position is per figure** (`build_inlay(individual_recess_positions=[...])`, one value per figure, falling back to the config value where an entry is missing; Web-App: selection above the slider, stored in `fig_offsets_dict`; CLI: `--finger-recess-position` takes one value or one per `-i` file). Radius, axis and Z offset stay global on purpose — they describe the hand, not the figure. The app's per-figure state init therefore sits directly after the file uploader: the recess controls are rendered further up the sidebar than the manual offsets and already need `fig_names`. -- **`build_inlay` does not grow the box for finger recesses on its own.** Both entry points get `stable_global_bounds` from `arrange_with_stable_bounds`, which pads XY by `clearance + voxel_pitch` and — with finger recesses — by `finger_radius` in X (otherwise the recesses cut through the side walls). The app passes the unrotated meshes as layout reference (stable slots while rotating), the CLI passes the rotated ones (rotation is fixed up front). -- **Stable means the slots, not the box.** The returned bounds always enclose the *actually arranged* meshes: XY is the union of the padded reference bounds and the real ones, Z comes from the real ones alone. Deriving the box from the unrotated reference used to size it for the ungrown figure — a 90° rotation put the figure outside the box and 20 mm above the floor. Don't "restore stability" by feeding reference bounds back into the box dimensions. -- **The Z bounds carry exactly one compensation: `voxel_pitch/2` per side.** That is the inflation `_solidify_figure` adds when it marching-cubes the cavity (measured cube == sphere == cylinder, 2026-08). Less and the floor comes out `voxel_pitch/2` too thin; the old `clearance + voxel_pitch` made it up to 2.5 mm too thick. `build_inlay`'s no-stable-bounds path adds the same `voxel_pitch` to its raw Z extent so both paths agree. -- **`inlay.metadata["max_z_extent"]` is the placement height** `build_inlay` actually used. The app's 3D preview must read it instead of recomputing the span from the figure bounds — otherwise it draws the figures at a different height than the real cavity. +- **Finger recesses** (`Config.enable_finger_recesses`, `Config.finger_radius`) are exposed in the Web-App and via the CLI flags `--finger-recesses` / `--finger-radius`. `build_inlay` communicates results back through `inlay.metadata`: `wall_check` (the full check, see below), `violating_indices` (figures with at least one finding), `placements` (per figure, the translation applied to the mesh passed in) and `finger_recesses` (recess meshes for the preview). +- **Two different knobs move the recesses.** `finger_recess_z_offset` (mm) sinks them below the box's top edge; `finger_recess_position` (`-1.0` … `1.0`) slides the pair *along* the figure, across `finger_recess_axis`, to pick the grip point. The latter is relative to the figure's usable half length (half extent minus `finger_radius`), not mm: one setting then fits figures of different sizes and `±1.0` keeps the hemisphere within the figure's own length. (Across that axis a figure narrower than `2 × finger_radius` is still exceeded by the recess - the box and the layout see it, because they are measured on the cutters.) The silhouette search band is centred on that grip position, so the recesses hug the figure where the fingers actually reach in. **The grip position is per figure** (`build_inlay(individual_recess_positions=[...])`, one value per figure, falling back to the config value where an entry is missing; Web-App: selection above the slider, stored per upload in `fig_offsets_dict`; CLI: `--finger-recess-position` takes one value or one per `-i` file). Radius, axis and Z offset stay global on purpose — they describe the hand, not the figure. The app's per-figure state init therefore sits directly after the file uploader: the recess controls are rendered further up the sidebar than the manual offsets and already need `fig_names`. +- **`build_inlay` arranges, dimensions and checks - from the real cutters.** Each figure sinks `depth_fraction` of its *own* height below the box's top face (a short figure next to a tall one used to get no pocket at all; an STL's absolute Z decided the box height). Its voxel solid plus its recesses form its cutter; `arrange_footprints` spaces the cutters' XY footprints exactly `figure_gap` apart, the box adds `wall_thickness` around them and below the deepest one. Voxelization shifts a cavity by up to half a pitch depending on where it lies on the grid - any box sized from a *predicted* inflation (the old `clearance + voxel_pitch` / `voxel_pitch/2` pads) was off by that much. So: solidify first, measure, then place. Don't reintroduce caller-side box bounds (`stable_global_bounds` / `arrange_with_stable_bounds` are gone on purpose) or inflation constants. +- **Manual offsets move a figure inside a fixed box.** The box is dimensioned before `individual_offsets` are applied; walls an offset makes too thin are findings of the wall check, not a reason to grow the box. +- **The layout follows the rotated figures; the unrotated ones only fix the order.** The app passes them as `sorting_reference`, so neighbours don't swap places while one figure is being rotated. Laying out the unrotated figures (the old "stable slots") let rotated cavities overlap by 18 mm with a green badge. +- **Cutters end `CUT_OVERSHOOT_MM` above the top face.** `_solidify_figure(..., top_z)` fills every column up past the top face (a figure ending below it left a sealed void), the recess template is a hemisphere with a vertical shaft (a lowered bare hemisphere had a roof). The automatic box height also keeps `wall_thickness` below the deepest recess. +- **`inlay.metadata["placements"]` is what the preview draws with.** The prepared figure shares its frame with the dilated one passed to `build_inlay`, so `fig.apply_translation(placements[i])` puts it exactly into its cavity. Don't re-derive the placement in the app. +- **The wall check is exact and per figure (`_wall_check`).** Each cutter is clipped to the box with manifold3d: side and floor walls come from the pocket's bounds (for the cylinder: apothem minus the farthest vertex), walls between pockets from `min_gap`, sealed voids from negative-volume shells. Findings (`side`, `floor`, `inner`, `merged`, `sealed`, `no_cavity`) carry the figure index. `passes_min_wall` means *no finding at all*; `WALL_TOLERANCE_MM` (0.05) only absorbs float32 rounding and the cylinder's chord error. `wall_thickness_stats_3d(inlay)` just reports it - there is no voxel fallback for meshes that did not come out of `build_inlay`. - **`build_inlay` never rotates.** Rotations are applied in step 1 via `apply_euler_rotation` and are already baked into the meshes handed to `build_inlay`. It used to accept an `individual_rotations` argument that was silently ignored — that parameter is gone; don't reintroduce it. - There are **two entry points:** - CLI: `python inlayer.py [-i figure.stl] [-o inlay.stl] [-c 0.4] [--lang de] …` — `--lang` is parsed *before* the main parser is built, because argparse renders help strings at construction time; `INLAYER_LANG` is the fallback. @@ -66,16 +73,19 @@ High-signal context for OpenCode sessions in this repo. - **Voxel dilation** is used for the tolerance offset (`dilate`) instead of normal-shifted surface offset. This is intentional: voxel offsetting survives cracks and non-manifold edges that vertex-normal offsets choke on. - **Voxel inflation is compensated in `dilate`.** Marching cubes inflates surfaces: ~`voxel_pitch/2` per side in `prepare_figure` plus ~`voxel_pitch/4` in `dilate`'s own reconstruction. Measured surplus without compensation: `0.75 * voxel_pitch`, geometry-independent (cube == sphere, 2026-07). `dilate` subtracts this from the requested distance; consequence: the effective clearance cannot drop below ~`0.75 * voxel_pitch`. -- **The layout gap compensates the dilation, and `clearance` is the wrong number for it.** `arrange_with_stable_bounds` widens the slot spacing by `2 × _dilation_steps(...)[1]` so the configured `figure_gap` survives the dilation. Use that helper, never `clearance`: `dilate` quantizes to `voxel_pitch/2` and has a floor, so the real per-side growth is `iters * pitch + pitch/2` — smaller than `clearance` in the usual range, *larger* below `voxel_pitch/4` (where a `2 × clearance` offset left the cavities overlapping). +- **The dilation is (nearly) isotropic.** scipy's default element (6-neighbourhood) grows an octahedron - 2 mm of clearance along the axes left 1.5 mm on a 45° slope. `dilate` does a share of `(√3 − 1)/2` of its steps with the full 3×3×3 cube, which makes axis and space-diagonal growth equal (every direction within 0.97–1.06). The growth *along the axes* stays one voxel per step, so `_dilation_iterations`' calibration holds. There is deliberately no `binary_closing` before the dilation: dilating a closing with the same element equals dilating the input (bit for bit), it only cost time. - **Pad voxel grids before morphological ops.** scipy's `binary_closing`/`binary_dilation` clip at array borders — without `np.pad` by the iteration count, the erosion step eats the figure's extremes (a sphere literally turns into a cube at coarse pitch). Both `prepare_figure` and `dilate` pad and then correct the grid transform for the padding offset. -- Boolean CSG operations use `engine='manifold'` explicitly (`trimesh.boolean.difference(..., engine='manifold')`). Do not rely on the default engine. +- Boolean CSG runs in manifold3d, never in trimesh's default engine: `build_inlay` calls `manifold3d` directly (`_to_manifold`/`_to_trimesh`, the same float32 conversion `trimesh.boolean` uses with `engine='manifold'`), because the wall check needs the `Manifold` objects anyway. ## Runtime notes - Voxel pitch (`Config.voxel_pitch`) trades resolution for memory non-linearly (O(n³)). Halving the pitch increases memory ~8×. -- `wall_thickness_stats_3d` tolerates a 0.1 mm undershoot due to voxel discretization (`passes_min_wall` uses `wall_thickness - 0.1`). - **Keep voxel operations vectorized.** Per-voxel work goes through numpy/scipy (`binary_closing`/`binary_dilation` with `iterations=`, `argmax`/`where=`-reductions) — never Python loops over voxel grids. Avoid allocating full-grid temporaries when a reduction or mask achieves the same. -- **Reuse geometry templates.** Primitives that are identical per figure (e.g. the finger-recess hemisphere in `build_inlay`) are built once and `copy()`-translated per use — don't recreate icospheres or run boolean ops inside the per-figure loop. -- **Optional multi-threading** (`Config.enable_parallel`, CLI `--parallel`, Web-App checkbox): per-figure steps (prepare, dilate, solidify) go through `_parallel_map`, which uses a `ThreadPoolExecutor` — plain threads suffice because numpy/scipy/trimesh release the GIL during C calls. Workers are capped at `MAX_PARALLEL_WORKERS = 4` because concurrent voxel grids multiply peak memory (O(n³)). In `app.py`, worker threads need the Streamlit ScriptRunContext attached (`_parallel_map_app`) so `st.cache_resource` calls work without warnings. +- **Reuse geometry templates.** Primitives that are identical per figure (e.g. the finger-recess template in `build_inlay`) are built once and `copy()`-translated per use — don't recreate icospheres or run boolean ops inside the per-figure loop. +- **Optional multi-threading** (`Config.enable_parallel`, CLI `--parallel`, Web-App checkbox): per-figure steps (prepare, dilate, solidify) go through `_parallel_map`, which uses a `ThreadPoolExecutor` — plain threads suffice because numpy/scipy/trimesh release the GIL during C calls. Workers are capped at `MAX_PARALLEL_WORKERS = 4` because concurrent voxel grids multiply peak memory (O(n³)). `app.py` uses the same `_parallel_map` and attaches the Streamlit ScriptRunContext through its `worker_init` hook (needed for `st.cache_resource` in worker threads) - it used to run its own pool, which skipped the language hand-over. - **`fast_simplification` is not thread-safe — decimate only through `inlayer.decimate_mesh`.** Its `simplify()` loads the mesh into process-global C++ state (`load` → `simplify` → `return_points`), so two concurrent calls hand *both* callers the mesh that was loaded last. With `--parallel` this produced an inlay whose cavities were all the same figure. `inlayer.decimate_mesh` serializes every call behind `_SIMPLIFY_LOCK`; `app_helpers.decimate_mesh` is a re-export of it. `trimesh.simplify_quadric_decimation` is a thin wrapper around the same library — calling it directly reopens the hole. (The bug only surfaced once `prepare_figure` started skipping `pymeshfix` for clean meshes: the repair step used to stagger the threads by seconds.) -- In `app.py`, expensive preview decimation must go through the cached `_decimated_for_viz(mesh, cache_key, face_count)` with a stable cache key (`{result_token}:{name}`), so Streamlit reruns don't re-decimate. +- In `app.py`, expensive preview decimation must go through the cached `_decimated_for_viz(mesh, cache_key, face_count)` with a stable cache key, so Streamlit reruns don't re-decimate. It returns `app_helpers.preview_copy`, a geometry-only copy: under the face budget `decimate_mesh` returns its input, and the process-wide cache then held whole meshes with their metadata. The result stored in the session keeps only what the view reads (decimated inlay, placements, recesses, stats). +- **Keys of process-wide caches identify the cached object by content, never by name or size.** `st.cache_resource` is shared by every session in the process: keyed by `name:size`, a second user uploading a different `model.stl` of the same size saw the first user's model. Uploads are identified by their content hash (`content_hashes[uf.file_id]`, computed once per upload); a cached figure's key carries everything that determines it (content hash, scale, pitch, decimation, rotation) - the inlay's hash does not determine a figure. +- **Never repair with pymeshfix's defaults.** `MeshFix.repair()` defaults to `remove_smallest_components=True`, which keeps only the shell with the most triangles: a holed figure lost its separate base (or, sorted by triangle count, its body). `prepare_figure` passes `remove_smallest_components=False`. +- **Raw input meshes are voxelized through `_voxelize_surface`, never `mesh.voxelized()`.** trimesh's voxelizer subdivides until every edge is below `pitch / 2`, so its cost grows with edge length² - a low-poly CAD rod took 1.95 GB, a 250 mm bar aborted. `_voxelize_surface` samples triangles in rows and scales with area. `dilate` and `_solidify_figure` may keep `mesh.voxelized()`: they voxelize marching-cubes output with edges of about one pitch. `_check_grid_size` refuses grids above `MAX_GRID_VOXELS` before anything is allocated. +- **Streamlit drops a widget's state while the widget is not rendered.** Values that must survive a hidden section live in plain session keys and the widget only writes through to them (`app._select`); otherwise hiding the rotation section reset the step to 45° and a stored 350° crashed every rerun. **Streamlit 1.62 also sends a selectbox value as its label**, so after a language switch the old label matches no option: every selectbox with translated labels goes through `_select` (raw value in a plain key, labels resolved once per run, unknown values map to no label). A lenient `format_func` (`"x" if a == "x" else `) turned the stale label into the value `"left/right"` and crashed the next run. diff --git a/Dockerfile b/Dockerfile index ed2d782..68df904 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,9 +4,12 @@ FROM python:3.13-slim AS base WORKDIR /app -# Systemabhängigkeiten fuer pymeshfix / manifold3d +# No compiler: every pinned requirement resolves as a cp313 wheel for x86_64 +# and aarch64 (pip install --dry-run --only-binary=:all:), and build-essential +# added ~350 MB plus a toolchain to the internet-facing image. Should a +# source build ever be needed, it belongs in a builder stage of its own. +# libgl1/libglib2.0-0 stay deliberately (see AGENTS.md, CI section). RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential \ libgl1 \ libglib2.0-0 \ && rm -rf /var/lib/apt/lists/* diff --git a/README.md b/README.md index 3a2d7e9..e26e388 100644 --- a/README.md +++ b/README.md @@ -180,14 +180,15 @@ The web app is a full GUI with live preview: | 🌍 **English / German** | Switch the interface language in the sidebar at any time | | 📂 **File upload** | Upload one or **several** STL models straight from the sidebar | | 🪞 **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live — without running the pipeline | -| 🧩 **Auto arrangement** | Multiple figures are placed without collisions (`compact` / `horizontal` / `vertical`) with an adjustable gap | +| 🧩 **Auto arrangement** | Multiple figures are placed without collisions (`compact` / `horizontal` / `vertical`) with an adjustable gap — it follows the wall thickness until you set it yourself | | 🎚️ **Interactive parameters** | Clearance, wall thickness, insert depth and voxel resolution via sliders | | 🎯 **Manual positioning** | Move each figure (or all of them together) in X/Y/Z inside the box | | 🔄 **Manual rotation** | Rotate each figure (or all of them together) about X/Y/Z | | 🖐️ **Finger recesses** | Optional hemispherical cut-outs beside each figure as a removal aid (adjustable radius, axis and depth; the position along the figure is set **per figure**) | | ⚡ **Multi-threading** | Optionally process several figures in parallel across CPU cores (checkbox in the sidebar) | | 📐 **Box overrides** | Optionally force fixed box dimensions | -| 🔍 **3D wall thickness check** | Automatic check with colour-coded warnings, stat cards and a pointer to the affected figures | +| 🧷 **Settings per file** | Offsets, rotations and grip positions belong to each upload — two files with the same name appear as `model.stl` and `model.stl (2)` and are positioned separately; a removed file takes its settings along | +| 🔍 **Wall check** | Every wall is measured on the finished geometry — sides, floor and the walls between cavities; each finding names its figure | | 👁️ **3D preview** | Interactive Plotly viewer (rotate, zoom, show/hide) | | 📥 **STL download** | Download the finished inlay as an STL | @@ -236,9 +237,20 @@ python inlayer.py --lang de -i figure.stl -o inlay.stl python inlayer.py --help ``` -The console shows progress messages, per-step timings and the wall thickness -check (warning if the minimum is not met). With several figures an extra -arrangement step (`2b`) appears. +The console shows progress messages, per-step timings and the wall check. +If the check fails, every finding is listed with its file name (e.g. +`fig2.stl: side wall 1.40 mm (target 2.00 mm)`) and the STL is still written so +you can inspect it. + +| Exit code | Meaning | +|---|---| +| `0` | Inlay written, wall check passed | +| `2` | Invalid arguments (argparse usage error) — nothing was computed | +| `3` | Inlay written, but the wall check found problems | + +All `--finger-recess-position` values are validated while parsing. Their count +(one, or one per `-i` file) only matters with `--finger-recesses`; without it +the positions have no effect and a note says so. --- @@ -249,14 +261,21 @@ The suite (`tests/`) covers config validation, every pipeline step individually (`app_helpers.py`), the translation table and both rendered UI languages, end-to-end runs and the CLI. +`tests/test_geometry_invariants.py` measures the **finished inlay** instead of +checking formulas: side and floor walls equal `wall_thickness`, the wall +between two cavities equals `figure_gap`, every figure gets a pocket of its own +depth, no cavity is sealed, no finger recess breaks through. The measuring +helpers (`tests/geometry_probe.py`: manifold3d booleans, ray casts, `min_gap`) +know nothing about how the pipeline built the part. + ```powershell # Install test dependencies (once) pip install -r requirements-dev.txt -# Full suite (~18 s) +# Full suite (~70 s) pytest -# Fast unit tests only (skips slow end-to-end / CLI runs) +# Faster: skips end-to-end / CLI runs and the finest-pitch geometry checks pytest -m "not slow" # A single file or test @@ -277,7 +296,7 @@ frontend testable. | Job | What it does | Why | |---|---|---| | `pytest (Python 3.13)` | Installs `requirements-dev.txt` on a plain runner and runs the suite | Fast feedback (~1 min) | -| `Docker test stage` | `docker build --target test .` | Runs the same suite inside the pinned `python:3.13-slim` image — the only place a broken version pin or a source file missing from the Dockerfile's `COPY` list shows up | +| `Docker test stage` | `docker build --target test .`, then `--target runtime` plus a smoke test (module imports, `/_stcore/health` of the running container) | Runs the same suite inside the pinned `python:3.13-slim` image — the only place a broken version pin or a source file missing from the Dockerfile's `COPY` list shows up — and proves the deploy image starts | Runs on the same branch supersede each other, so an outdated commit does not keep a runner busy. @@ -286,8 +305,8 @@ keep a runner busy. ## 🔧 Pipeline -`inlayer.py` runs the following steps (step 2b only with several figures). Each -figure can optionally be rotated beforehand via `apply_euler_rotation`: +`inlayer.py` runs the following steps. Each figure can optionally be rotated +beforehand via `apply_euler_rotation`: ``` STL file(s) @@ -307,33 +326,40 @@ STL file(s) └──────────────────────┬───────────────────────────────────────────┘ ▼ ┌──────────────────────────────────────────────────────────────────┐ -│ 2b. arrange_with_stable_bounds │ -│ collision-free XY arrangement on a stable slot grid │ -│ (compact / horizontal / vertical, adjustable gap) │ -└──────────────────────┬───────────────────────────────────────────┘ - ▼ -┌──────────────────────────────────────────────────────────────────┐ │ 3. build_inlay │ -│ construct cuboid or cylinder, boolean difference via │ -│ manifold3d (all figures at once, box dimensions automatic │ -│ or manual, optional finger recesses as cut-outs) │ +│ sink every figure by depth_fraction of its own height, │ +│ solidify it up through the top face (+ finger recesses), │ +│ arrange the real cavities figure_gap apart (compact / │ +│ horizontal / vertical), build the cuboid or cylinder around │ +│ them, boolean difference via manifold3d, exact wall check │ └──────────────────────┬───────────────────────────────────────────┘ ▼ ┌──────────────────────────────────────────────────────────────────┐ │ 4. wall_thickness_stats_3d │ -│ compute 3D wall thickness from the cavity grid of step 3 │ -│ and check it against wall_thickness │ +│ report the check of step 3: thinnest wall, findings per │ +│ figure (side, floor, between cavities, sealed, no cavity) │ └──────────────────────┬───────────────────────────────────────────┘ ▼ inlay.stl ``` +Library use follows the same order: + +```python +fig = inlayer.apply_euler_rotation(inlayer.prepare_figure("figure.stl", cfg), 0, 0, 90) +inlay, w, d, h = inlayer.build_inlay([inlayer.dilate(fig, cfg.clearance, cfg)], cfg) +report = inlayer.wall_thickness_stats_3d(inlay) # also in inlay.metadata["wall_check"] +``` + --- ## 📐 Parameters All parameters flow through the frozen `Config` dataclass (CLI flags / web-app -sidebar). +sidebar). Values are validated up front: lengths must be > 0 (`clearance` and +`finger_recess_z_offset` ≥ 0), `depth_fraction` in (0, 1], `decimate_faces` +≥ 4, and NaN or infinity is rejected everywhere. The CLI reports an invalid +value as a usage error before any work starts. ### Print settings @@ -341,7 +367,7 @@ sidebar). |---|---|---| | `clearance` | 0.4 mm | Clearance between figure and cavity | | `wall_thickness` | 2.0 mm | Minimum side and floor wall thickness | -| `depth_fraction` | 0.7 | Fraction of the figure's height inside the cavity (30 % stands proud) | +| `depth_fraction` | 0.7 | Fraction of **each** figure's own height inside its cavity (30 % stands proud) | ### Mesh processing @@ -393,8 +419,12 @@ sidebar). | `finger_recess_z_offset` / `--finger-recess-z-offset` | 0.0 mm | How far the recesses sit below the box's top edge (e.g. to touch only the cap on keycaps) | | `finger_recess_position` / `--finger-recess-position` | 0.0 | Position of the recesses **along** the figure, `-1.0` … `1.0` (`0.0` = centre; web-app slider: −100 … +100 %). Set **per figure** — see below | -> With finger recesses enabled the box grows by `2 × finger_radius` along the -> recess axis, so the recesses lie entirely within the box walls. +> With finger recesses enabled the box encloses the recesses in **both** axes — +> including figures narrower than the recess — and keeps `wall_thickness` below +> the deepest recess (the automatic box height grows if necessary; with a +> manual height a recess that would break through is reported by the wall +> check). A recess lowered by `finger_recess_z_offset` gets a vertical shaft up +> to the top face, so it stays open and prints without an overhang. > The recesses are placed where the figure is widest at the grip position (across > the recess axis). The width of that search band scales with `voxel_pitch` @@ -421,7 +451,8 @@ sidebar). > or one value per `-i` file, in that order. Any other count is an error rather > than a guess. > - **API:** `build_inlay(..., individual_recess_positions=[...])` — figures -> without an entry fall back to `Config.finger_recess_position`. +> without an entry fall back to `Config.finger_recess_position`. App and CLI +> always pass the per-figure list. ### Language (optional) @@ -453,18 +484,22 @@ sidebar). ## ⚠️ Technical notes +- **Even clearance on slopes:** the tolerance offset grows the figure by the same amount in every direction (within about 5 %). The plain voxel dilation used before grew an octahedron — with 2 mm of clearance a figure got only about 1.5 mm on 45° slopes and could jam there. - **Voxel scaling:** voxel-based steps scale O(n³) with resolution. Halving `VOXEL_PITCH` raises memory use by roughly 8×. - **trimesh 4.x quirk:** `VoxelGrid.marching_cubes` does not apply the grid transform to the vertices. The code therefore calls `apply_transform(vox.transform)` manually after every `marching_cubes` call. -- **CSG engine:** boolean operations explicitly use `engine='manifold'` (`manifold3d`). manifold3d already parallelises internally across cores. +- **CSG engine:** boolean operations run in `manifold3d` (directly, never trimesh's default engine). manifold3d already parallelises internally across cores. - **Multi-threading:** the optional parallelisation (`--parallel` / web-app checkbox) uses a `ThreadPoolExecutor` — numpy/scipy/trimesh release the GIL during their C calls, so threads give real multi-core speedup without process overhead. With parallelisation enabled, log lines from individual figures can interleave. - **Decimation is serialised:** `fast_simplification` (also behind `trimesh.simplify_quadric_decimation`) loads the mesh into process-global state. Concurrent calls from several threads therefore hand *every* caller the same mesh — with `--parallel` this produced an inlay whose cavities all showed the same figure. All decimation now goes through `inlayer.decimate_mesh` behind a lock; only the remaining steps (voxelisation, dilation, solidification) still run in parallel. - **Language and threads:** the selected language lives in a `ContextVar`, not a module global, so two Streamlit sessions cannot overwrite each other's choice. `ThreadPoolExecutor` workers start with a fresh context and do *not* inherit it — `_parallel_map` therefore captures the language and re-applies it inside each worker, otherwise parallel steps would log in the default language. -- **Figure gap vs. dilation:** `figure_gap` refers to the distance between the *dilated* figures, i.e. the wall between two cavities. The slot grid is therefore spaced wider than the configured value by twice the dilation growth — at identical settings the box comes out correspondingly larger than before this correction. The growth is derived from `dilate` (quantised to `voxel_pitch/2`, with a lower bound) rather than equated with `clearance`: at `clearance < voxel_pitch/4` the allowance would otherwise be too small and the cavities would run into each other. With a manually set box width, shelf packing reserves wall thickness **plus** padding on each side — fewer figures may fit per row, but the box keeps its specified size. -- **Box dimensions follow the rotated figure:** the web app uses the *unrotated* figures as the layout reference so slots do not jump while rotating. Only the slots are stable, though — the box dimensions come from the figures as actually arranged. Previously they came from the unrotated reference too: a figure rotated by 90° got a box sized for its unrotated extent, stuck out at the sides and floated well above the floor. Consequence of the fix: box dimensions now visibly change when a rotation makes the figure larger or smaller. -- **Box height and floor wall:** `depth_fraction` refers to the figure height plus `voxel_pitch`. The allowance compensates for the inflation that the marching-cubes reconstruction in `_solidify_figure` applies to the cavity — without it the floor comes out `voxel_pitch/2` thinner than configured. This used to include the full bounds padding (`clearance + voxel_pitch` per side), which made the floor about 1 mm too thick at default settings and over 2 mm at a coarse pitch. At identical settings the box therefore comes out slightly flatter than before this correction. -- **Repair only when needed:** `prepare_figure` skips `pymeshfix` when the loaded mesh is already watertight **and** consistently wound — the normal case for cleanly exported STLs. That halves the step's runtime (measured 1.99 s → 1.08 s at 82k triangles) and does not change the geometry. Watertightness alone is not a sufficient criterion: a mesh with inverted faces is watertight but would corrupt the subsequent voxel fill. -- **Wall thickness tolerance:** `wall_thickness_stats_3d` tolerates 0.1 mm below target to account for voxel discretisation. -- **Wall check without voxelising the inlay:** `build_inlay` builds the cavity grid (`inlay.metadata["cavity_grid"]`) directly from the subtracted figures. `wall_thickness_stats_3d` uses that grid and no longer has to voxelise the finished inlay itself — which saved double-digit gigabytes of RAM and several minutes of runtime on large figures. The old voxel path remains as a fallback only for inlays without this metadata (e.g. STLs loaded directly). +- **Measured, not predicted:** `build_inlay` solidifies every figure first and then arranges and dimensions the box from those real cavities. Voxelisation shifts a cavity by up to half a `voxel_pitch` depending on where it lies on the grid, so every box sized from a predicted allowance was off by that much: side walls came out 1.75–2.4 mm and floors 2.2–2.6 mm for a 2 mm target, and the wall between two cavities `figure_gap − voxel_pitch`. Now side and floor walls are `wall_thickness` and the wall between cavities is `figure_gap` — the invariant tests measure exactly that. At identical settings boxes can therefore come out slightly smaller or larger than before. +- **Box height:** every figure sinks `depth_fraction` of its own height below the top face, wherever its STL sits in Z. The floor is `wall_thickness` under the deepest cavity; shorter figures sit on a thicker floor. Previously all figures were aligned at their tops against the tallest one — a short figure next to a tall one got no pocket at all, and two figures at different Z origins produced a solid block. +- **Rotation and layout:** the layout uses the rotated figures, so rotated cavities never overlap; the web app uses the unrotated figures only to keep the *order* stable while you rotate. Previously the slots came from the unrotated figures and a rotation could merge two cavities. +- **Manual offsets** move a figure inside a box that stays put; walls made too thin that way are reported by the check. +- **Cavities stay open:** each cavity is extruded up through the top face. With `depth_fraction = 1.0` and a negative Z offset the pocket used to close at the top — a sealed void in the print. +- **Repair only when needed:** `prepare_figure` skips `pymeshfix` when the loaded mesh is already watertight **and** consistently wound — the normal case for cleanly exported STLs. That halves the step's runtime (measured 1.99 s → 1.08 s at 82k triangles) and does not change the geometry. Watertightness alone is not a sufficient criterion: a mesh with inverted faces is watertight but would corrupt the subsequent voxel fill. When the repair does run, it keeps **every** shell of the file: pymeshfix's default drops all but the shell with the most triangles, so a miniature with a separate base used to lose the base as soon as the file had a single hole anywhere. +- **Low-poly meshes:** input meshes are voxelised by sampling each triangle in rows along its longest edge, so the cost follows the surface area. trimesh's own voxeliser subdivides until *every* edge is below `voxel_pitch / 2`, which costs (edge length / pitch)² per triangle — the long, thin triangles of CAD exports (rods, pins, profiles) took gigabytes or aborted with "max_iter exceeded". A figure whose voxel grid would exceed `MAX_GRID_VOXELS` (10⁹ voxels at `voxel_pitch / 2`, the finest grid in the pipeline) is refused with a message suggesting a larger pitch, instead of exhausting the machine's memory. +- **Broken files:** an empty or unreadable STL is rejected with a message naming the file. In the web app the instant preview skips such a file with a warning and still shows the others. +- **Wall check:** measured exactly on the meshes (manifold3d) while `build_inlay` still has every figure's cutter: side and floor walls per figure, the wall between each pair of cavities, sealed voids and figures without a cavity. Each finding names its figure; `passes_min_wall` is true only without any finding. The tolerance is 0.05 mm (float rounding, the cylinder's chord error). The earlier voxel-based check overestimated walls by up to one pitch, ignored the walls between cavities and passed an inlay without any cavity. --- diff --git a/app.py b/app.py index a50c22a..dfcceed 100644 --- a/app.py +++ b/app.py @@ -17,12 +17,9 @@ import io import os import time -import hashlib import tempfile import threading -from concurrent.futures import ThreadPoolExecutor -import numpy as np import plotly.graph_objects as go import streamlit as st import trimesh @@ -99,7 +96,7 @@ def _cached_prepare( _path: str, file_hash: str, scale: float, pitch: float, decimate_faces: int ) -> trimesh.Trimesh: - """Schritt 1 wird zwischengespeichert, wenn sich Eingabedatei / Parameter nicht ändern.""" + """Step 1, cached as long as file content and parameters stay the same.""" config = inlayer.Config( stl_unit_to_mm=scale, voxel_pitch=pitch, decimate_faces=decimate_faces ) @@ -118,50 +115,43 @@ def _cached_dilate( rot_y: float, rot_z: float, ) -> trimesh.Trimesh: - """Schritt 2 (Dilation) wird zwischengespeichert, wenn sich Figur / clearance / pitch / rotation nicht ändern.""" + """Step 2, cached as long as figure, clearance, pitch and rotation stay the same.""" config = inlayer.Config(voxel_pitch=pitch) return inlayer.dilate(_mesh, clearance, config) _file_hash = app_helpers.file_hash - -def _parallel_map_app(fn, items): - """Fuehrt fn parallel ueber items aus (ThreadPool) und reicht den - Streamlit-ScriptRunContext an die Worker-Threads weiter, damit - st.cache_resource-Aufrufe dort ohne Warnung funktionieren.""" - ctx = get_script_run_ctx() - - def _with_ctx(item): - if ctx is not None: - add_script_run_ctx(threading.current_thread(), ctx) - return fn(item) - - workers = inlayer._effective_workers(len(items)) - with ThreadPoolExecutor(max_workers=workers) as ex: - return list(ex.map(_with_ctx, items)) +# Face budget of the inlay in the result view +INLAY_PREVIEW_FACES = 30000 @st.cache_resource(show_spinner=False, max_entries=64) def _decimated_for_viz( _mesh: trimesh.Trimesh, cache_key: str, face_count: int ) -> trimesh.Trimesh: - """Dezimiert ein Mesh fuer die 3D-Vorschau (gecacht ueber cache_key). + """Decimated copy of a figure for the 3D preview, cached under cache_key. - cache_key identifiziert das Ergebnis-Mesh stabil, sodass die teure - Dezimierung bei reinen Reruns (z.B. Widget-Interaktionen) nicht erneut laeuft. + Shared by every session in the process: the key has to name everything + that determines the mesh (see "fig_cache_keys" below). """ - return app_helpers.decimate_mesh(_mesh, face_count) + return app_helpers.preview_copy(_mesh, face_count) @st.cache_resource(show_spinner=False, max_entries=32) -def _preview_mesh(_data: bytes, cache_key: str, scale: float) -> trimesh.Trimesh: - """Laedt eine hochgeladene STL dezimiert fuer die Sofort-Vorschau (gecacht).""" - return app_helpers.load_preview_mesh(_data, scale) +def _preview_mesh(_data: bytes, content_hash: str, scale: float, _name: str) -> trimesh.Trimesh: + """Loads an uploaded STL, decimated, for the instant preview (cached). + + The cache is process-wide, so the key must identify the mesh by content: + keyed by name and size, a second user uploading a different `model.stl` + of the same size was shown the first user's model. With a content hash a + session only ever gets a cached object for bytes it uploaded itself. + """ + return app_helpers.load_preview_mesh(_data, scale, _name) -# --- Plotly-Helfer ------------------------------------------------------------ -# Farbpalette fuer Figuren-Traces (Sofort-Vorschau und Ergebnis-Ansicht) +# --- Plotly helpers --------------------------------------------------------- +# Colour palette of the figure traces (instant preview and result view) _fig_colors = [ "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#bcbd22", "#17becf", @@ -169,7 +159,7 @@ def _preview_mesh(_data: bytes, cache_key: str, scale: float) -> trimesh.Trimesh def _mesh3d(mesh: trimesh.Trimesh, **kwargs) -> go.Mesh3d: - """Plotly-Mesh3d-Trace aus einem trimesh-Mesh.""" + """Plotly Mesh3d trace of a trimesh mesh.""" return go.Mesh3d( x=mesh.vertices[:, 0], y=mesh.vertices[:, 1], z=mesh.vertices[:, 2], i=mesh.faces[:, 0], j=mesh.faces[:, 1], k=mesh.faces[:, 2], @@ -194,6 +184,10 @@ def log(self, msg, t0=None): # --- UI --------------------------------------------------------------------- +# Every widget has a fixed, language-independent key. Streamlit derives the +# identity of an unkeyed widget from its label - which is translated, so a +# language switch created new widgets: the uploads vanished and every setting +# fell back to its default. tests/test_app_render.py fails on an unkeyed widget. st.markdown('
Inlayer 3D
', unsafe_allow_html=True) st.markdown( f'
{t("app.subtitle")}
', @@ -210,115 +204,239 @@ def log(self, msg, t0=None): st.sidebar.markdown(t("app.sidebar.pipeline_params")) uploaded_files = st.sidebar.file_uploader( - t("app.upload.label"), type=["stl"], accept_multiple_files=True, -) -# Leere Liste normalisieren -if not uploaded_files: - uploaded_files = [] + t("app.upload.label"), type=["stl"], accept_multiple_files=True, key="uploads", +) or [] multi_mode = len(uploaded_files) > 1 if multi_mode: st.sidebar.info(t("app.upload.multi_info", n=len(uploaded_files))) -# Session state. Deliberately right after the upload instead of further down: -# the finger recess controls above it in the sidebar already address individual -# figures and need fig_names. -fig_names = [uf.name for uf in uploaded_files] if uploaded_files else ["figur.stl"] -if "fig_offsets_dict" not in st.session_state: - st.session_state["fig_offsets_dict"] = {} - -for name in fig_names: - if name not in st.session_state["fig_offsets_dict"]: - st.session_state["fig_offsets_dict"][name] = {} - for k, default_val in [ - ("offset_x", 0.0), ("offset_y", 0.0), ("offset_z", 0.0), - ("rot_x", 0.0), ("rot_y", 0.0), ("rot_z", 0.0), - ("finger_recess_position", 0.0), - ]: - if k not in st.session_state["fig_offsets_dict"][name]: - st.session_state["fig_offsets_dict"][name][k] = default_val - -# A removed upload must not leave a dangling selection behind: Streamlit rejects -# a session-state value that is not among a selectbox's options. The equivalent -# reset for the position/rotation selections follows further down, next to them. -if st.session_state.get("selected_recess_fig") not in [ALL_FIGURES] + fig_names: - st.session_state["selected_recess_fig"] = ALL_FIGURES - - -def _fig_label(name: str) -> str: - """Label of a figure selection: sentinel translated, file names raw. - - Defined this early because the finger recess selection above already - formats with it. +# Content hash per upload, computed once per upload rather than on every rerun. +# It is the identity of a file in every process-wide cache key and in the +# staleness snapshot - name and size are not (see _preview_mesh). +_known_hashes = st.session_state.get("_hash_by_file_id", {}) +content_hashes = { + uf.file_id: _known_hashes.get(uf.file_id) or app_helpers.bytes_hash(uf.getvalue()) + for uf in uploaded_files +} +st.session_state["_hash_by_file_id"] = content_hashes + +# --- Per-figure state ------------------------------------------------------- +# Deliberately right after the upload: the finger recess controls sit further +# up the sidebar than the manual offsets and already address single figures. +# A figure is identified by its upload (file_id), not its file name: two +# different model.stl files used to share one entry and moved together. The +# option values are ids (like ALL_FIGURES, never translated); _fig_label shows +# the name. +FALLBACK_ID = "__fallback__" +OFFSET_AXES, ROTATION_AXES = app_helpers.OFFSET_AXES, app_helpers.ROTATION_AXES +fig_ids = [uf.file_id for uf in uploaded_files] or [FALLBACK_ID] +_labels = dict(zip( + fig_ids, + app_helpers.figure_labels([uf.name for uf in uploaded_files]) or [inlayer.DEFAULT_INPUT], +)) + +stored = st.session_state.setdefault("fig_offsets_dict", {}) +# A removed upload takes its settings along; uploaded again, it starts fresh. +for _gone in set(stored) - set(fig_ids): + del stored[_gone] +for _fid in fig_ids: + stored.setdefault(_fid, dict(app_helpers.FIGURE_DEFAULTS)) + + +_labels[ALL_FIGURES] = t("app.all_figures") + + +def _fig_label(fid: str) -> str: + """Label of a figure option: sentinel translated, uploads by unique name.""" + return _labels.get(fid, fid) + + +def _select(label: str, labels: dict, key: str, default, **kwargs): + """Selectbox over `labels` (value -> display text) whose value lives in a + plain session key (`key`). + + Streamlit drops a widget's state while the widget is not rendered, and it + sends a selectbox's value as its *label*. Hiding the rotation section put + the step back to 45° (a stored 350° then exceeded the slider's max and + every rerun raised); after a language switch the old label matched no + option - a lenient format_func turned "left/right" into the recess axis, + a strict one reset the box shape to its default. So the raw value is kept + here, seeds `index`, and the widget only writes through. The labels are + resolved once per run and unknown values map to no label at all. + """ + st.session_state.setdefault(key, default) + widget_key = f"_w_{key}" + options = list(labels) + return st.sidebar.selectbox( + label, options, + index=options.index(st.session_state[key]), + format_func=lambda v: labels.get(v, str(v)), + key=widget_key, + on_change=lambda: st.session_state.update({key: st.session_state[widget_key]}), + **kwargs, + ) + + +def _step_select(label: str, options: list[float], unit: str, step_key: str) -> float: + """Step size of the offset or rotation sliders.""" + return float(_select(label, {x: f"{int(x)}{unit}" for x in options}, + step_key, STEP_DEFAULTS[step_key])) + + +STEP_DEFAULTS = {"rot_step": 45.0, "pos_step": 10.0} +for _step_key, _step_default in STEP_DEFAULTS.items(): + st.session_state.setdefault(_step_key, _step_default) + + +def _quantize_axis(axis: str, val: float) -> float: + """Quantizes with the current step size of the axis kind.""" + step_key = "rot_step" if app_helpers.is_rotation_axis(axis) else "pos_step" + return app_helpers.quantize_axis_value(axis, val, float(st.session_state[step_key])) + + +def _requantize_axes(axes: tuple[str, ...]): + """Snaps every stored value and every display key to the current step. + + Runs on every rerun, before the sliders exist: that keeps what the sliders + show and what the pipeline reads identical, and keeps each value inside + its slider's range whatever step it was stored with. """ - return t("app.all_figures") if name == ALL_FIGURES else name + for offsets in stored.values(): + for axis in axes: + offsets[axis] = _quantize_axis(axis, offsets.get(axis, 0.0)) + for axis in axes: + if axis in st.session_state: + val = _quantize_axis(axis, st.session_state[axis]) + st.session_state[axis] = val + st.session_state[f"_sl_{axis}"] = val + st.session_state[f"_ni_{axis}"] = val + + +RECESS_SELECT = "selected_recess_fig" +# Widget key of the recess position: one slider for every figure, loaded with +# the selected figure's stored value. +RECESS_POS_KEY = "_sl_finger_recess_position" +_selection_key = app_helpers.selection_key + + +def _targets(sel_key: str) -> list[str]: + """The figures a change of that control writes to.""" + return app_helpers.resolve_selection( + st.session_state.get(sel_key, ALL_FIGURES), fig_ids, ALL_FIGURES + )[2] + + +def _load_axes(ref: str, axes: tuple[str, ...]): + for axis in axes: + value = stored[ref][axis] + st.session_state[axis] = value + st.session_state[f"_sl_{axis}"] = value + st.session_state[f"_ni_{axis}"] = value + + +def _load_recess(ref: str): + st.session_state[RECESS_POS_KEY] = int(round(stored[ref]["finger_recess_position"] * 100)) + + +def _store_axis_value(axis: str, val: float): + """Quantizes the value, mirrors it into all its widget keys and stores it + for the currently selected figure(s).""" + val = _quantize_axis(axis, val) + st.session_state[axis] = val + st.session_state[f"_sl_{axis}"] = val + st.session_state[f"_ni_{axis}"] = val + for fid in _targets(_selection_key(axis)): + stored[fid][axis] = val + + +def _sync_from_slider(axis: str): + _store_axis_value(axis, st.session_state[f"_sl_{axis}"]) + + +def _sync_from_input(axis: str): + _store_axis_value(axis, st.session_state[f"_ni_{axis}"]) + + +def _store_recess_position(): + """Writes the slider value to the currently selected figure(s).""" + value = float(st.session_state[RECESS_POS_KEY]) / 100.0 + for fid in _targets(RECESS_SELECT): + stored[fid]["finger_recess_position"] = value + + +_requantize_axes(OFFSET_AXES + ROTATION_AXES) + +# Bring every selection - and the widgets it drives - in line with the current +# uploads, before any widget exists (Streamlit forbids setting widget state +# afterwards). The widgets are reloaded from the stored values whenever the +# figure they show changes: a figure was removed, the first one changed under +# "all figures", a selection was reset - or their state was dropped while +# hidden. The selection callbacks alone missed all of that: the sliders kept +# the previous figure's values while the pipeline used the stored ones. +for _sel_key, _load, _shown in ( + (RECESS_SELECT, _load_recess, [RECESS_POS_KEY]), + ("selected_fig", lambda ref: _load_axes(ref, OFFSET_AXES), + [f"_{w}_{a}" for a in OFFSET_AXES for w in ("sl", "ni")]), + ("selected_rot_fig", lambda ref: _load_axes(ref, ROTATION_AXES), + [f"_{w}_{a}" for a in ROTATION_AXES for w in ("sl", "ni")]), +): + _selection, _ref, _ = app_helpers.resolve_selection( + st.session_state.get(_sel_key, ALL_FIGURES), fig_ids, ALL_FIGURES + ) + st.session_state[_sel_key] = _selection + if st.session_state.get(f"_ref_{_sel_key}") != _ref or any( + k not in st.session_state for k in _shown + ): + _load(_ref) + st.session_state[f"_ref_{_sel_key}"] = _ref + + +def _figure_select(label: str, sel_key: str): + """Selection "all figures" / one figure - only offered with several figures.""" + if len(fig_ids) > 1: + st.sidebar.selectbox( + label, [ALL_FIGURES] + fig_ids, format_func=_fig_label, key=sel_key, + ) + st.sidebar.markdown("---") st.sidebar.markdown(t("app.printer.heading")) clearance = st.sidebar.slider( t("app.clearance.label"), min_value=0.1, max_value=2.0, value=0.4, step=0.1, - help=t("app.clearance.help"), + help=t("app.clearance.help"), key="clearance", ) wall_thickness = st.sidebar.slider( t("app.wall_thickness.label"), min_value=1.0, max_value=5.0, value=2.0, step=0.5, - help=t("app.wall_thickness.help"), + help=t("app.wall_thickness.help"), key="wall_thickness", ) depth_fraction = st.sidebar.slider( t("app.depth_fraction.label"), min_value=0.3, max_value=1.0, value=0.7, step=0.05, - help=t("app.depth_fraction.help"), + help=t("app.depth_fraction.help"), key="depth_fraction", ) voxel_pitch = st.sidebar.slider( t("app.voxel_pitch.label"), min_value=0.2, max_value=1.0, value=0.4, step=0.1, - help=t("app.voxel_pitch.help"), + help=t("app.voxel_pitch.help"), key="voxel_pitch", ) decimate_faces = st.sidebar.number_input( t("app.decimate_faces.label"), min_value=5000, max_value=50000, value=20000, step=5000, - help=t("app.decimate_faces.help"), + help=t("app.decimate_faces.help"), key="decimate_faces", ) scale = st.sidebar.number_input( t("app.scale.label"), min_value=0.01, max_value=100.0, value=1.0, step=0.1, - help=t("app.scale.help"), + help=t("app.scale.help"), key="scale", ) # --- Finger recesses: position per figure ----------------------------------- -# Widget key of the recess position. A single key (not one per figure), reloaded -# whenever the figure selection changes - same approach as the manual offsets. -RECESS_POS_KEY = "_sl_finger_recess_position" - - -def _recess_percent(name: str) -> int: - """A figure's stored recess position as the slider's percent value.""" - stored = st.session_state["fig_offsets_dict"].get(name, {}).get("finger_recess_position", 0.0) - return int(round(float(stored) * 100)) - - -def _store_recess_position(): - """Writes the slider value to the currently selected figure(s).""" - value = float(st.session_state[RECESS_POS_KEY]) / 100.0 - _, targets = app_helpers.recess_position_targets( - st.session_state.get("selected_recess_fig", ALL_FIGURES), fig_names, ALL_FIGURES - ) - for name in targets: - st.session_state["fig_offsets_dict"][name]["finger_recess_position"] = value - - -def _on_recess_fig_selected(): - """Loads the newly selected figure's stored value into the slider.""" - ref, _ = app_helpers.recess_position_targets( - st.session_state.get("selected_recess_fig", ALL_FIGURES), fig_names, ALL_FIGURES - ) - st.session_state[RECESS_POS_KEY] = _recess_percent(ref) - - enable_finger_recesses = st.sidebar.checkbox( t("app.finger.enable.label"), value=False, help=t("app.finger.enable.help"), + key="finger_enabled", ) finger_radius = 8.0 finger_recess_axis = "x" finger_recess_z_offset = 0.0 -finger_recess_position = 0.0 if enable_finger_recesses: finger_radius = st.sidebar.slider( t("app.finger.radius.label"), @@ -327,11 +445,11 @@ def _on_recess_fig_selected(): value=8.0, step=0.5, help=t("app.finger.radius.help"), + key="finger_radius", ) - finger_recess_axis = st.sidebar.selectbox( + finger_recess_axis = _select( t("app.finger.axis.label"), - options=["x", "y"], - format_func=lambda a: t("app.finger.axis.x") if a == "x" else t("app.finger.axis.y"), + {"x": t("app.finger.axis.x"), "y": t("app.finger.axis.y")}, "finger_axis", "x", help=t("app.finger.axis.help"), ) finger_recess_z_offset = st.sidebar.slider( @@ -341,30 +459,13 @@ def _on_recess_fig_selected(): value=0.0, step=0.5, help=t("app.finger.z_offset.help"), + key="finger_z_offset", ) # Position along the figure. Unlike radius, axis and depth this one is # stored per figure: the best grip point follows the figure's shape, so one # shared value is wrong as soon as two differently shaped models share an - # inlay. Same slider-plus-selection pattern as the manual offsets further - # down (store on change, load on selection change) - but with its own - # callbacks, because _axis_row quantizes in mm/degrees, which does not fit - # a relative position. - if len(fig_names) > 1: - st.sidebar.selectbox( - t("app.finger.position.select_fig"), - [ALL_FIGURES] + fig_names, - format_func=_fig_label, - key="selected_recess_fig", - on_change=_on_recess_fig_selected, - ) - _recess_ref, _ = app_helpers.recess_position_targets( - st.session_state.get("selected_recess_fig", ALL_FIGURES), fig_names, ALL_FIGURES - ) - if RECESS_POS_KEY not in st.session_state: - st.session_state[RECESS_POS_KEY] = _recess_percent(_recess_ref) - - # Percent in the UI, fraction (-1.0 ... 1.0) in the pipeline - the slider is - # the more readable unit, the pipeline works relative to the half length. + # inlay. Percent in the UI, fraction (-1.0 ... 1.0) in the pipeline. + _figure_select(t("app.finger.position.select_fig"), RECESS_SELECT) st.sidebar.slider( t("app.finger.position.label"), min_value=-100, @@ -374,9 +475,6 @@ def _on_recess_fig_selected(): on_change=_store_recess_position, help=t("app.finger.position.help"), ) - # No write-through outside the callback: with "all figures" selected that - # would overwrite every per-figure value on each rerun. - finger_recess_position = st.session_state[RECESS_POS_KEY] / 100.0 st.sidebar.markdown("---") st.sidebar.markdown(t("app.performance.heading")) @@ -384,16 +482,14 @@ def _on_recess_fig_selected(): t("app.parallel.label"), value=False, help=t("app.parallel.help", workers=inlayer.MAX_PARALLEL_WORKERS), + key="parallel", ) st.sidebar.markdown("---") st.sidebar.markdown(t("app.box.heading")) -box_shape = st.sidebar.selectbox( +box_shape = _select( t("app.box.shape.label"), - options=["box", "cylinder"], - format_func=lambda x: t(f"app.box.shape.{x}"), - index=0, - key="box_shape", + {"box": t("app.box.shape.box"), "cylinder": t("app.box.shape.cylinder")}, "box_shape", "box", help=t("app.box.shape.help"), ) use_custom_box = st.sidebar.checkbox(t("app.box.custom.label"), value=False, key="use_custom_box") @@ -413,29 +509,34 @@ def _on_recess_fig_selected(): st.sidebar.markdown("---") st.sidebar.markdown(t("app.position.heading")) -# Callbacks für Figurenabstand-Synchronisierung + def _sync_gap_from_slider(): val = st.session_state["_sl_figure_gap"] st.session_state["figure_gap"] = val st.session_state["_ni_figure_gap"] = val + st.session_state["_gap_user_set"] = True + def _sync_gap_from_input(): val = st.session_state["_ni_figure_gap"] st.session_state["figure_gap"] = val st.session_state["_sl_figure_gap"] = val + st.session_state["_gap_user_set"] = True -# figure_gap: nur bei mehreren Figuren relevant, aber immer verfügbar + +# figure_gap only matters with several figures if multi_mode: - if "figure_gap" not in st.session_state: - st.session_state["figure_gap"] = wall_thickness - if "_sl_figure_gap" not in st.session_state: - st.session_state["_sl_figure_gap"] = float(st.session_state["figure_gap"]) - if "_ni_figure_gap" not in st.session_state: - st.session_state["_ni_figure_gap"] = float(st.session_state["figure_gap"]) - - # Gemeinsame Beschriftung fuer Slider + Zahlenfeld (beide mit - # label_visibility="collapsed"). Keine feste Farbe: der Text muss der - # Theme-Textfarbe folgen, sonst ist er im hellen Theme unlesbar. + # The gap defaults to the wall thickness and keeps following it until the + # user sets one of their own - as the help text and the CLI say. It used + # to be copied once, so changing the wall thickness left the gap behind. + if not st.session_state.get("_gap_user_set"): + for _key in ("figure_gap", "_sl_figure_gap", "_ni_figure_gap"): + st.session_state[_key] = float(wall_thickness) + for _key in ("_sl_figure_gap", "_ni_figure_gap"): + st.session_state.setdefault(_key, float(st.session_state["figure_gap"])) + + # One caption for slider and number field (both label_visibility="collapsed"). + # No fixed colour: the text has to follow the theme's text colour. st.sidebar.markdown( f'{t("app.gap.label")}', unsafe_allow_html=True @@ -464,143 +565,31 @@ def _sync_gap_from_input(): else: figure_gap = None -layout_style = st.sidebar.selectbox( +layout_style = _select( t("app.layout.label"), - options=["compact", "horizontal", "vertical"], - format_func=lambda x: t(f"app.layout.{x}"), - index=0, - key="layout_style", - help=t("app.layout.help") + {x: t(f"app.layout.{x}") for x in ("compact", "horizontal", "vertical")}, "layout_style", "compact", + help=t("app.layout.help"), ) if multi_mode else "compact" -# Falls die ausgewählte Figur nicht mehr existiert, auf die erste zurücksetzen -valid_fig_names = [ALL_FIGURES] + fig_names if len(fig_names) > 1 else fig_names -if "selected_fig" in st.session_state and st.session_state["selected_fig"] not in valid_fig_names: - st.session_state["selected_fig"] = valid_fig_names[0] - -selected_fig = st.session_state.get("selected_fig", valid_fig_names[0]) -if selected_fig not in valid_fig_names: - selected_fig = valid_fig_names[0] - st.session_state["selected_fig"] = selected_fig - -# --- Callback-Helfer (Slider ↔ Eingabefeld ↔ fig_offsets_dict) -------------- -# Rotationsachsen tragen das Praefix "rot_" und werden modulo 360 quantisiert; -# Positionsachsen ("offset_") werden auf die jeweilige Schrittweite gerundet. - -def _quantize_axis(axis: str, val: float) -> float: - """Holt die Schrittweite aus dem Session-State und quantisiert damit.""" - if app_helpers.is_rotation_axis(axis): - step = float(st.session_state.get("rot_step_size", 45.0)) - else: - step = float(st.session_state.get("pos_step_size", 10.0)) - return app_helpers.quantize_axis_value(axis, val, step) - -_selection_key = app_helpers.selection_key - - -def _store_axis_value(axis: str, val: float): - """Quantisiert den Wert, spiegelt ihn in alle Widget-Keys und speichert ihn - fuer die aktuell ausgewaehlte(n) Figur(en) im fig_offsets_dict.""" - val = _quantize_axis(axis, val) - st.session_state[axis] = val - st.session_state[f"_sl_{axis}"] = val - st.session_state[f"_ni_{axis}"] = val - selected = st.session_state.get(_selection_key(axis), ALL_FIGURES) - offsets_dict = st.session_state.get("fig_offsets_dict", {}) - targets = fig_names if selected == ALL_FIGURES else [selected] - for name in targets: - if name in offsets_dict: - offsets_dict[name][axis] = val - -def _sync_from_slider(axis: str): - _store_axis_value(axis, st.session_state[f"_sl_{axis}"]) - -def _sync_from_input(axis: str): - _store_axis_value(axis, st.session_state[f"_ni_{axis}"]) - -def _load_axes_from_selection(axes: list[str]): - """Laedt die gespeicherten Werte der ausgewaehlten Figur in die Widgets.""" - selected = st.session_state.get(_selection_key(axes[0]), ALL_FIGURES) - ref = fig_names[0] if selected == ALL_FIGURES else selected - offsets = st.session_state.get("fig_offsets_dict", {}).get(ref) - if not offsets: - return - for axis in axes: - st.session_state[axis] = offsets[axis] - st.session_state[f"_sl_{axis}"] = offsets[axis] - st.session_state[f"_ni_{axis}"] = offsets[axis] - -def _requantize_axes(axes: list[str]): - """Snappt alle gespeicherten Werte der Achsen auf die neue Schrittweite.""" - offsets_dict = st.session_state.get("fig_offsets_dict", {}) - for name in fig_names: - if name in offsets_dict: - for axis in axes: - offsets_dict[name][axis] = _quantize_axis(axis, offsets_dict[name].get(axis, 0.0)) - for axis in axes: - if axis in st.session_state: - val = _quantize_axis(axis, st.session_state[axis]) - st.session_state[axis] = val - st.session_state[f"_sl_{axis}"] = val - st.session_state[f"_ni_{axis}"] = val - -def _on_fig_selected(): - _load_axes_from_selection(["offset_x", "offset_y", "offset_z"]) - -def _on_rot_fig_selected(): - _load_axes_from_selection(["rot_x", "rot_y", "rot_z"]) - -def _on_rot_step_change(): - _requantize_axes(["rot_x", "rot_y", "rot_z"]) - -def _on_pos_step_change(): - _requantize_axes(["offset_x", "offset_y", "offset_z"]) - - -# Sicherstellen, dass die Werte für das aktuelle Widget geladen sind -# 1. Positionen -selected_pos_fig = st.session_state.get("selected_fig", ALL_FIGURES) -ref_pos_fig = fig_names[0] if selected_pos_fig == ALL_FIGURES else selected_pos_fig -if ref_pos_fig not in fig_names: - ref_pos_fig = fig_names[0] -offsets_pos = st.session_state["fig_offsets_dict"][ref_pos_fig] -for axis in ["offset_x", "offset_y", "offset_z"]: - if axis not in st.session_state: - st.session_state[axis] = offsets_pos[axis] - if f"_sl_{axis}" not in st.session_state: - st.session_state[f"_sl_{axis}"] = offsets_pos[axis] - if f"_ni_{axis}" not in st.session_state: - st.session_state[f"_ni_{axis}"] = offsets_pos[axis] - -# 2. Rotationen -selected_rot_fig = st.session_state.get("selected_rot_fig", ALL_FIGURES) -ref_rot_fig = fig_names[0] if selected_rot_fig == ALL_FIGURES else selected_rot_fig -if ref_rot_fig not in fig_names: - ref_rot_fig = fig_names[0] -offsets_rot = st.session_state["fig_offsets_dict"][ref_rot_fig] -for axis in ["rot_x", "rot_y", "rot_z"]: - if axis not in st.session_state: - st.session_state[axis] = offsets_rot[axis] - if f"_sl_{axis}" not in st.session_state: - st.session_state[f"_sl_{axis}"] = offsets_rot[axis] - if f"_ni_{axis}" not in st.session_state: - st.session_state[f"_ni_{axis}"] = offsets_rot[axis] - -# Manuelle Positionierung / Rotation (pro Figur oder fuer alle) def _axis_row(axis: str, label: str, lo: float, hi: float, step: float, hint: str): - """Slider + Zahlenfeld fuer eine Achse, synchronisiert ueber die _sync-Callbacks.""" + """Slider + number field of one axis, kept in sync through _store_axis_value. + + No `value=`: the keys are always set before the widgets exist (see the + selection sync above), and a default next to a state value only earns a + Streamlit warning. + """ c1, c2 = st.sidebar.columns([3, 1]) with c1: st.slider( - label, lo, hi, float(st.session_state[axis]), step, + label, lo, hi, step=step, key=f"_sl_{axis}", on_change=_sync_from_slider, args=(axis,), help=hint, ) with c2: st.number_input( - label, lo, hi, float(st.session_state[axis]), step, + label, lo, hi, step=step, key=f"_ni_{axis}", on_change=_sync_from_input, args=(axis,), label_visibility="collapsed", @@ -611,28 +600,12 @@ def _axis_row(axis: str, label: str, lo: float, hi: float, step: float, hint: st t("app.manual_offsets.label"), value=False, help=t("app.manual_offsets.help"), + key="manual_offsets", ) if enable_manual_offsets: - if len(fig_names) > 1: - st.sidebar.selectbox( - t("app.select_fig_position"), - [ALL_FIGURES] + fig_names, - format_func=_fig_label, - key="selected_fig", - on_change=_on_fig_selected, - ) - - # Schrittweite für Positionierung - st.sidebar.selectbox( - t("app.pos_step.label"), - options=[1.0, 5.0, 10.0], - format_func=lambda x: f"{int(x)} mm", - index=2, - key="pos_step_size", - on_change=_on_pos_step_change, - ) - pos_step = float(st.session_state.get("pos_step_size", 10.0)) + _figure_select(t("app.select_fig_position"), "selected_fig") + pos_step = _step_select(t("app.pos_step.label"), [1.0, 5.0, 10.0], " mm", "pos_step") _axis_row("offset_x", t("app.offset_x.label"), -100.0, 100.0, pos_step, t("app.offset_x.help")) @@ -646,57 +619,35 @@ def _axis_row(axis: str, label: str, lo: float, hi: float, step: float, hint: st t("app.manual_rotations.label"), value=False, help=t("app.manual_rotations.help"), + key="manual_rotations", ) if enable_manual_rotations: - rot_options = [ALL_FIGURES] + fig_names if len(fig_names) > 1 else fig_names - st.sidebar.selectbox( - t("app.select_fig_rotation"), - rot_options, - format_func=_fig_label, - key="selected_rot_fig", - on_change=_on_rot_fig_selected, - ) - - # Schrittweite für Drehung - st.sidebar.selectbox( - t("app.rot_step.label"), - options=[1.0, 5.0, 10.0, 45.0], - format_func=lambda x: f"{int(x)}°", - index=3, - key="rot_step_size", - on_change=_on_rot_step_change, - ) - rot_step = float(st.session_state.get("rot_step_size", 45.0)) + _figure_select(t("app.select_fig_rotation"), "selected_rot_fig") + rot_step = _step_select(t("app.rot_step.label"), [1.0, 5.0, 10.0, 45.0], "°", "rot_step") max_rot = 360.0 - rot_step _axis_row("rot_x", t("app.rot_x.label"), 0.0, max_rot, rot_step, t("app.rot_x.help")) _axis_row("rot_y", t("app.rot_y.label"), 0.0, max_rot, rot_step, t("app.rot_y.help")) _axis_row("rot_z", t("app.rot_z.label"), 0.0, max_rot, rot_step, t("app.rot_z.help")) -offset_x = st.session_state["offset_x"] if enable_manual_offsets else 0.0 -offset_y = st.session_state["offset_y"] if enable_manual_offsets else 0.0 -offset_z = st.session_state["offset_z"] if enable_manual_offsets else 0.0 +# The per-figure values the pipeline really uses - the run, the instant preview +# and the staleness check all read these, never a slider. +applied = app_helpers.applied_figure_params( + stored, fig_ids, enable_manual_offsets, enable_manual_rotations, enable_finger_recesses +) def _params_snapshot() -> dict: - """Snapshot aller ergebnisrelevanten Eingaben. - - Wird beim Generieren im Ergebnis gespeichert und beim Rendern mit den - aktuellen Widget-Werten verglichen, um veraltete Ergebnisse zu erkennen. - enable_parallel fehlt bewusst - es aendert nur die Laufzeit.""" - per_fig = {} - for name in fig_names: - off = st.session_state["fig_offsets_dict"].get(name, {}) - per_fig[name] = ( - (off.get("offset_x", 0.0), off.get("offset_y", 0.0), off.get("offset_z", 0.0)) - if enable_manual_offsets else (0.0, 0.0, 0.0), - (off.get("rot_x", 0.0), off.get("rot_y", 0.0), off.get("rot_z", 0.0)) - if enable_manual_rotations else (0.0, 0.0, 0.0), - off.get("finger_recess_position", 0.0) if enable_finger_recesses else 0.0, - ) + """Everything a result depends on, for the "settings changed" check. + + Stored with the result and compared on every render. Built from the + applied per-figure values: which figure a slider happens to show is not a + change (switching the recess selection used to mark the result stale). + enable_parallel is left out on purpose - it only changes the runtime. + """ return { - "files": [(uf.name, uf.size) for uf in uploaded_files], + "files": [(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files], "clearance": clearance, "wall_thickness": wall_thickness, "depth_fraction": depth_fraction, @@ -706,15 +657,17 @@ def _params_snapshot() -> dict: "box": (box_shape, box_width, box_depth, box_height, box_diameter), "figure_gap": figure_gap, "layout_style": layout_style, - "finger": (enable_finger_recesses, finger_radius if enable_finger_recesses else None, finger_recess_axis if enable_finger_recesses else None, finger_recess_z_offset if enable_finger_recesses else None, finger_recess_position if enable_finger_recesses else None), - "per_fig": per_fig, + "finger": (finger_radius, finger_recess_axis, finger_recess_z_offset) + if enable_finger_recesses else None, + "per_fig": applied, } -# Hauptbereich + +# Main area col_left, col_right = st.columns([1, 2]) with col_left: st.markdown(t("app.run.heading")) - run_btn = st.button(t("app.run.button"), width="stretch") + run_btn = st.button(t("app.run.button"), width="stretch", key="run") st.markdown(t("app.run.log_heading")) status_box = st.empty() status_box.info(t("app.run.waiting")) @@ -729,21 +682,24 @@ def _params_snapshot() -> dict: if run_btn: tmp_paths: list[str] = [] try: - # Datei-Vorbereitung: mehrere Uploads oder Fallback auf figur.stl - fallback_path = "figur.stl" + # Input: the uploads, or the default file next to the app + fallback_path = inlayer.DEFAULT_INPUT input_paths: list[str] = [] file_names: list[str] = [] + file_hashes: list[str] = [] if uploaded_files: for uf in uploaded_files: with tempfile.NamedTemporaryFile(suffix=".stl", delete=False) as tmp: - tmp.write(uf.getbuffer()) + tmp.write(uf.getvalue()) tmp_paths.append(tmp.name) input_paths.append(tmp_paths[-1]) - file_names.append(uf.name) + file_names.append(_labels[uf.file_id]) + file_hashes.append(content_hashes[uf.file_id]) elif os.path.exists(fallback_path): input_paths = [fallback_path] file_names = [fallback_path] + file_hashes = [_file_hash(fallback_path)] else: st.error(t("app.error.no_input", path=fallback_path)) st.stop() @@ -765,161 +721,116 @@ def _params_snapshot() -> dict: box_depth=box_depth, box_height=box_height, box_diameter=box_diameter, - offset_x=offset_x, - offset_y=offset_y, - offset_z=offset_z, figure_gap=figure_gap, layout_style=layout_style, enable_finger_recesses=enable_finger_recesses, finger_radius=finger_radius, finger_recess_axis=finger_recess_axis, finger_recess_z_offset=finger_recess_z_offset, - finger_recess_position=finger_recess_position, enable_parallel=enable_parallel, ) - # Gesamtfortschrittsbalken progress = st.progress(0, text=t("app.progress.start")) + rotations = [a["rotation"] for a in applied] - # Individuelle manuelle Offsets & Rotationen ermitteln - individual_offsets = [] - individual_rotations = [] - individual_recess_positions = [] - for name in file_names: - if enable_manual_offsets: - off = st.session_state["fig_offsets_dict"].get(name, {}) - individual_offsets.append((off.get("offset_x", 0.0), off.get("offset_y", 0.0), off.get("offset_z", 0.0))) - else: - individual_offsets.append((0.0, 0.0, 0.0)) - - if enable_manual_rotations: - off = st.session_state["fig_offsets_dict"].get(name, {}) - individual_rotations.append((off.get("rot_x", 0.0), off.get("rot_y", 0.0), off.get("rot_z", 0.0))) - else: - individual_rotations.append((0.0, 0.0, 0.0)) - - off = st.session_state["fig_offsets_dict"].get(name, {}) - individual_recess_positions.append( - float(off.get("finger_recess_position", 0.0)) if enable_finger_recesses else 0.0 - ) + # Worker threads need the ScriptRunContext for st.cache_resource; the + # language is handed over by _parallel_map itself. + _ctx = get_script_run_ctx() - # Datei-Hashes einmal vorab berechnen (Cache-Keys, je Datei nur ein Read) - file_hashes = [_file_hash(p) for p in input_paths] + def _attach_ctx(): + if _ctx is not None: + add_script_run_ctx(threading.current_thread(), _ctx) - # Schritt 1: Alle Figuren vorbereiten und ggf. rotieren (optional parallel) + # Step 1: prepare and, if requested, rotate every figure label = (t("app.label.figures", n=n_files) if is_multi else t("app.label.figure")) progress.progress(0.20, text=t("app.progress.step1", label=label)) t_step = logger.log(t("app.log.prepare", label=label)) + if enable_parallel and is_multi: + logger.log(t("app.log.parallel", n=n_files, + workers=inlayer._effective_workers(n_files))) def _prepare_one(i: int): + if is_multi and not enable_parallel: + logger.log(t("app.log.figure_n", i=i + 1, n=n_files, name=file_names[i])) mesh = _cached_prepare( input_paths[i], file_hashes[i], scale, voxel_pitch, decimate_faces ) - rx, ry, rz = individual_rotations[i] - rotated = mesh - if rx != 0.0 or ry != 0.0 or rz != 0.0: - rotated = inlayer.apply_euler_rotation(mesh, rx, ry, rz) + rotated = inlayer.apply_euler_rotation(mesh, *rotations[i]) if any(rotations[i]) else mesh return mesh, rotated - if enable_parallel and is_multi: - logger.log(t("app.log.parallel", n=n_files, - workers=inlayer._effective_workers(n_files))) - prepared_pairs = _parallel_map_app(_prepare_one, list(range(n_files))) - else: - prepared_pairs = [] - for i in range(n_files): - if is_multi: - logger.log(t("app.log.figure_n", i=i + 1, n=n_files, name=file_names[i])) - prepared_pairs.append(_prepare_one(i)) + prepared_pairs = inlayer._parallel_map( + _prepare_one, range(n_files), config, worker_init=_attach_ctx + ) unrotated_fig_meshes = [pair[0] for pair in prepared_pairs] fig_meshes = [pair[1] for pair in prepared_pairs] - # Schritt 2: Toleranz-Offset pro Figur (optional parallel) + # Step 2: tolerance offset per figure progress.progress(0.40, text=t("app.progress.step2")) t_step = logger.log(t("app.log.dilate"), t_step) - - def _dilate_one(i: int): - rx, ry, rz = individual_rotations[i] - return _cached_dilate( + dilated = inlayer._parallel_map( + lambda i: _cached_dilate( fig_meshes[i], file_hashes[i], scale, voxel_pitch, decimate_faces, - clearance, rx, ry, rz, - ) - - if enable_parallel and is_multi: - fig_offsets = _parallel_map_app(_dilate_one, list(range(n_files))) - else: - fig_offsets = [_dilate_one(i) for i in range(n_files)] - - # Schritt 2b: Stabile Anordnung + Box-Bounds (geteilte Logik mit der CLI). - # Referenz sind die unrotierten Figuren, damit Slots und Box-Masse bei - # Rotationsaenderungen einzelner Figuren stabil bleiben. - if is_multi: - gap = config.figure_gap if config.figure_gap is not None else config.wall_thickness - progress.progress(0.55, text=t("app.progress.step2b", n=n_files)) - t_step = logger.log(t("app.log.arrange", n=n_files, gap=f"{gap:.1f}", - style=config.layout_style), t_step) - fig_offsets, stable_global_bounds, auto_xy_translations = ( - inlayer.arrange_with_stable_bounds( - unrotated_fig_meshes, fig_meshes, fig_offsets, config - ) + clearance, *rotations[i], + ), + range(n_files), config, what=t("pipeline.what.dilate"), worker_init=_attach_ctx, ) - # xy_translations und z_offsets für Speicherung/Visualisierung setzen (Auto-Anordnung + manueller Offset) - xy_translations = [ - auto_xy_translations[i] + np.array([individual_offsets[i][0], individual_offsets[i][1]]) - for i in range(n_files) - ] - z_offsets = [individual_offsets[i][2] for i in range(n_files)] - - # Schritt 3: Inlay konstruieren + # Step 3: build_inlay arranges the figures on their real cavities, + # builds the box around them and checks every wall. The unrotated + # figures only fix the layout order, so neighbours do not swap places + # while one of them is being rotated. progress.progress(0.70, text=t("app.progress.step3")) t_step = logger.log(t("app.log.build"), t_step) inlay, actual_w, actual_d, actual_h = inlayer.build_inlay( - fig_offsets, config, individual_offsets=individual_offsets, - individual_recess_positions=individual_recess_positions, - stable_global_bounds=stable_global_bounds, + dilated, config, + individual_offsets=[a["offset"] for a in applied], + individual_recess_positions=[a["recess_position"] for a in applied], file_names=file_names, + sorting_reference=unrotated_fig_meshes, ) - # Berechne die Nullpunkt-Verschiebung fuer die 3D-Vorschau - bmin, bmax = stable_global_bounds - shift_x = (bmin[0] + bmax[0]) / 2 - actual_w / 2 - shift_y = (bmin[1] + bmax[1]) / 2 - actual_d / 2 - - # Schritt 4: Wandstärkenprüfung + # Step 4: wall check (ran inside build_inlay, reported here) progress.progress(0.90, text=t("app.progress.step4")) t_step = logger.log(t("app.log.wall_check"), t_step) - stats_3d = inlayer.wall_thickness_stats_3d(inlay, config) + stats_3d = inlayer.wall_thickness_stats_3d(inlay) progress.progress(1.0, text=t("app.progress.done")) logger.log(t("app.progress.done"), t_start) - # --- Ergebnisse im session_state speichern --- stl_io = io.BytesIO() inlay.export(file_obj=stl_io, file_type="stl") - stl_data = stl_io.getvalue() + # Only what the result view reads, as geometry-only copies: the full + # inlay (and before that the dilated figures) sat in every session's + # state although the view needs a decimated mesh and a few numbers. st.session_state["result"] = { "params": _params_snapshot(), - "result_token": hashlib.sha256(stl_data).hexdigest()[:16], "stats_3d": stats_3d, "box_shape": box_shape, "actual_w": actual_w, "actual_d": actual_d, "actual_h": actual_h, - "stl_bytes": stl_data, + "stl_bytes": stl_io.getvalue(), + "n_faces": len(inlay.faces), "wall_thickness": wall_thickness, - "depth_fraction": depth_fraction, - "inlay": inlay, + "inlay_viz": app_helpers.preview_copy(inlay, INLAY_PREVIEW_FACES), + "placements": inlay.metadata["placements"], + "recesses": [ + app_helpers.preview_copy(r, INLAY_PREVIEW_FACES) + for r in inlay.metadata.get("finger_recesses", []) + ], "fig_meshes": fig_meshes, - "fig_offsets": fig_offsets, + # Everything that determines a prepared, rotated figure. The inlay's + # hash does not: two figures on the same round base cut the same + # inlay, and the preview then drew the other session's figure. + "fig_cache_keys": [ + f"{file_hashes[i]}:{scale}:{voxel_pitch}:{decimate_faces}:" + + ":".join(str(r) for r in rotations[i]) + for i in range(n_files) + ], "file_names": file_names, "is_multi": is_multi, - "xy_translations": xy_translations, - "z_offsets": z_offsets, - "shift_x": float(shift_x), - "shift_y": float(shift_y), } except Exception as e: @@ -934,7 +845,7 @@ def _dilate_one(i: int): pass -# --- Dashboard & Vorschau (aus session_state, überlebt Reruns) -------------- +# --- Dashboard & preview (from session_state, survives reruns) -------------- if "result" in st.session_state: res = st.session_state["result"] stats_3d = res["stats_3d"] @@ -943,17 +854,9 @@ def _dilate_one(i: int): actual_h = res["actual_h"] stl_bytes = res["stl_bytes"] _wt = res["wall_thickness"] - inlay = res["inlay"] fig_meshes = res["fig_meshes"] - fig_offsets = res["fig_offsets"] _file_names = res["file_names"] _is_multi = res["is_multi"] - _df = res["depth_fraction"] - xy_trans = res.get("xy_translations", [np.array([0.0, 0.0])] * len(fig_meshes)) - z_offs = res.get("z_offsets", [0.0] * len(fig_meshes)) - _sx = res.get("shift_x", 0.0) - _sy = res.get("shift_y", 0.0) - _token = res.get("result_token", "") with col_left: st.markdown(t("app.results.heading")) @@ -969,20 +872,10 @@ def _dilate_one(i: int): f'
{t("app.results.wall_thin")}
', unsafe_allow_html=True, ) - # Ermittle betroffene Dateinamen aus den Metadaten des Inlays - violating_names = [] - violating_indices = inlay.metadata.get("violating_indices", []) if hasattr(inlay, "metadata") else [] - for idx in violating_indices: - if idx < len(_file_names): - violating_names.append(_file_names[idx]) - - affected_text = "" - if violating_names: - affected_text = t("app.results.affected", names=", ".join(violating_names)) - - st.warning(t("app.results.wall_warning", wall=_wt, - measured=f"{stats_3d['min_wall_mm']:.2f}", - affected=affected_text)) + findings = "\n".join( + "- " + inlayer.describe_violation(v, _file_names) for v in stats_3d["violations"] + ) + st.warning(t("app.results.wall_warning", wall=_wt, findings=findings)) st.write("") m_col1, m_col2 = st.columns(2) @@ -994,11 +887,10 @@ def _dilate_one(i: int): """, unsafe_allow_html=True, ) - _n_faces = f"{len(inlay.faces):,}".replace(",", ".") st.markdown( f"""
{t("app.metric.triangles")}
-
{_n_faces}
+
{i18n.format_int(res["n_faces"])}
""", unsafe_allow_html=True, ) @@ -1036,39 +928,26 @@ def _dilate_one(i: int): file_name=_dl_name, mime="application/octet-stream", width="stretch", + key="download", ) - # --- 3D Visualisierung ------------------------------------------------- + # --- 3D view ------------------------------------------------------------ with col_right: plot_box.empty() - - viz_inlay = _decimated_for_viz(inlay, f"{_token}:inlay", 30000) - fig_3d = go.Figure() - - # Inlay-Trace fig_3d.add_trace(_mesh3d( - viz_inlay, color="#1f77b4", opacity=0.8, + res["inlay_viz"], color="#1f77b4", opacity=0.8, name=t("app.trace.inlay"), showlegend=True, )) - # Figuren-Traces: jede Figur in eigener Farbe + # One colour per figure max_fig_faces = 15000 if not _is_multi else 10000 - - # Exakt die Z-Ausdehnung, mit der build_inlay die Figuren platziert hat. - # Nicht nachrechnen: die Bounds enthalten einen Inflations-Ausgleich, - # ohne den die Vorschau die Figuren zu tief in der Box zeichnet. - max_z_extent = float(inlay.metadata["max_z_extent"]) - - for i, (fig_m, fig_ot) in enumerate(zip(fig_meshes, fig_offsets)): - # Dezimierung (gecacht) vor der Translation – beides ist reihenfolgeunabhaengig - viz_fig = _decimated_for_viz(fig_m, f"{_token}:fig{i}", max_fig_faces).copy() - bmin_ot_z = float(fig_ot.bounds[0][2]) - trans_x = xy_trans[i][0] - _sx - trans_y = xy_trans[i][1] - _sy - fig_h = float(fig_ot.bounds[1][2] - fig_ot.bounds[0][2]) - z_pos_bottom = actual_h + (1 - _df) * max_z_extent - fig_h - viz_fig.apply_translation([trans_x, trans_y, z_pos_bottom - bmin_ot_z + z_offs[i]]) + # Exactly the translation build_inlay applied to each figure. The + # prepared figure shares its frame with the dilated one it was given, + # so the same translation puts it inside its cavity. + for i, fig_m in enumerate(fig_meshes): + viz_fig = _decimated_for_viz(fig_m, res["fig_cache_keys"][i], max_fig_faces).copy() + viz_fig.apply_translation(res["placements"][i]) color = _fig_colors[i % len(_fig_colors)] label = (_file_names[i] if i < len(_file_names) @@ -1080,47 +959,41 @@ def _dilate_one(i: int): viz_fig, color=color, opacity=0.6, name=label, showlegend=True, )) - # Fingermulden-Traces visualisieren, falls vorhanden - recesses = inlay.metadata.get("finger_recesses", []) if hasattr(inlay, "metadata") else [] - if recesses: - for r_idx, cyl in enumerate(recesses): - # Dezimierung gecacht, damit sie bei reinen Reruns nicht erneut laeuft - viz_cyl = _decimated_for_viz(cyl, f"{_token}:recess{r_idx}", 5000) - - fig_3d.add_trace(_mesh3d( - viz_cyl, color="#f1c40f", opacity=0.3, - name=t("app.trace.recesses"), showlegend=(r_idx == 0), - )) + for r_idx, recess in enumerate(res["recesses"]): + fig_3d.add_trace(_mesh3d( + recess, color="#f1c40f", opacity=0.3, + name=t("app.trace.recesses"), showlegend=(r_idx == 0), + )) fig_3d.update_layout(**_scene_layout(650)) st.plotly_chart(fig_3d, width="stretch") st.info(t("app.viewer.hint")) elif uploaded_files: - # --- Sofort-Vorschau: Figuren direkt nach dem Upload anzeigen ------------ - # Zeigt die (dezimierten) Original-Meshes nebeneinander, inkl. der aktuell - # eingestellten Rotationen – ohne die teure Pipeline zu starten. + # --- Instant preview: the figures right after the upload ----------------- + # Shows the (decimated) original meshes side by side, with the rotations + # currently set - without running the expensive pipeline. with col_right: prev_fig = go.Figure() cur_x = 0.0 for i, uf in enumerate(uploaded_files): - mesh = _preview_mesh(bytes(uf.getbuffer()), f"{uf.name}:{uf.size}", scale) - rot = st.session_state["fig_offsets_dict"].get(uf.name, {}) - rx = rot.get("rot_x", 0.0) if enable_manual_rotations else 0.0 - ry = rot.get("rot_y", 0.0) if enable_manual_rotations else 0.0 - rz = rot.get("rot_z", 0.0) if enable_manual_rotations else 0.0 - # apply_euler_rotation liefert immer eine Kopie – wichtig, weil - # _preview_mesh ein gecachtes Objekt zurueckgibt - mesh = inlayer.apply_euler_rotation(mesh, rx, ry, rz) + # One broken file must not take the preview of the others with it. + try: + mesh = _preview_mesh(uf.getvalue(), content_hashes[uf.file_id], scale, uf.name) + except ValueError as exc: + st.warning(str(exc)) + continue + # apply_euler_rotation always returns a copy - important, because + # _preview_mesh hands out a cached object + mesh = inlayer.apply_euler_rotation(mesh, *applied[i]["rotation"]) mesh.apply_translation( [cur_x - mesh.bounds[0][0], -mesh.bounds[0][1], -mesh.bounds[0][2]] ) cur_x += mesh.extents[0] + 10.0 prev_fig.add_trace(_mesh3d( mesh, color=_fig_colors[i % len(_fig_colors)], opacity=0.9, - name=uf.name, showlegend=True, + name=_labels[uf.file_id], showlegend=True, )) prev_fig.update_layout(**_scene_layout(650)) plot_box.plotly_chart(prev_fig, width="stretch") st.caption(t("app.preview.caption")) - diff --git a/app_helpers.py b/app_helpers.py index fa7c23c..969cc28 100644 --- a/app_helpers.py +++ b/app_helpers.py @@ -27,7 +27,7 @@ import hashlib import io -from typing import cast + import trimesh @@ -54,28 +54,72 @@ def file_hash(path: str) -> str: return h.hexdigest()[:_HASH_HEX_LEN] +def bytes_hash(data: bytes) -> str: + """Same digest as `file_hash`, for content already in memory (uploads).""" + return hashlib.sha256(data).hexdigest()[:_HASH_HEX_LEN] + + def selection_key(axis: str) -> str: """Liefert den Session-Key der zugehoerigen Figur-Auswahl.""" return "selected_rot_fig" if axis.startswith("rot_") else "selected_fig" -def recess_position_targets( - selected: str, fig_names: list[str], all_sentinel: str -) -> tuple[str, list[str]]: - """Resolves the figure selection of the finger recess position control. +OFFSET_AXES = ("offset_x", "offset_y", "offset_z") +ROTATION_AXES = ("rot_x", "rot_y", "rot_z") +# What a new upload starts with. Settings belong to one upload (its file_id): +# two different files called model.stl must not move together, and a removed +# file must not bring its old settings back when it is uploaded again. +FIGURE_DEFAULTS = {**{a: 0.0 for a in OFFSET_AXES + ROTATION_AXES}, "finger_recess_position": 0.0} + + +def figure_labels(names: list[str]) -> list[str]: + """Display names; a repeated file name gets a counter ("model.stl (2)").""" + seen: dict[str, int] = {} + labels = [] + for name in names: + seen[name] = seen.get(name, 0) + 1 + labels.append(name if seen[name] == 1 else f"{name} ({seen[name]})") + return labels - Returns the reference figure whose stored value the slider shows, and the - figures a change writes to. The "all figures" sentinel reads from the first - figure and writes to every one of them; a stale selection (a figure that was - removed from the upload) falls back to the first figure instead of raising. + +def resolve_selection( + selected: str, fig_ids: list[str], all_sentinel: str +) -> tuple[str, str, list[str]]: + """Resolves a figure selection against the current uploads. + + Returns (valid selection, reference figure whose stored values the widgets + show, figures a change writes to). The "all figures" sentinel reads from + the first figure and writes to all; a selection whose upload is gone falls + back to the sentinel. One rule for all three per-figure controls (recess + position, offsets, rotation) - they used to handle a removed upload in + three different ways, one of them not at all. """ - if not fig_names: + if not fig_ids: raise ValueError(t("error.no_meshes")) - if selected == all_sentinel: - return fig_names[0], list(fig_names) - if selected not in fig_names: - return fig_names[0], [fig_names[0]] - return selected, [selected] + if selected not in fig_ids: + return all_sentinel, fig_ids[0], list(fig_ids) + return selected, selected, [selected] + + +def applied_figure_params( + stored: dict[str, dict], fig_ids: list[str], + offsets: bool, rotations: bool, recesses: bool, +) -> list[dict]: + """The per-figure values the pipeline really uses, in upload order. + + A disabled feature counts as zero, whatever is stored. The run, the + instant preview and the "settings changed" check all read this - never + the slider, which only shows the currently selected figure. + """ + applied = [] + for fid in fig_ids: + s = {**FIGURE_DEFAULTS, **stored.get(fid, {})} + applied.append({ + "offset": tuple(float(s[a]) for a in OFFSET_AXES) if offsets else (0.0, 0.0, 0.0), + "rotation": tuple(float(s[a]) for a in ROTATION_AXES) if rotations else (0.0, 0.0, 0.0), + "recess_position": float(s["finger_recess_position"]) if recesses else 0.0, + }) + return applied def is_rotation_axis(axis: str) -> bool: @@ -104,14 +148,24 @@ def quantize_axis_value(axis: str, val: float, step: float) -> float: decimate_mesh = inlayer.decimate_mesh -def load_preview_mesh(data: bytes, scale: float) -> trimesh.Trimesh: - """Laedt eine hochgeladene STL dezimiert fuer die Sofort-Vorschau.""" - # force="mesh" garantiert ein Trimesh, der Typ von trimesh.load ist aber - # Geometry – gleiche cast-Konvention wie in inlayer.prepare_figure. - mesh = cast( - trimesh.Trimesh, - trimesh.load(io.BytesIO(data), file_type="stl", force="mesh"), - ) +def preview_copy(mesh: trimesh.Trimesh, face_count: int) -> trimesh.Trimesh: + """A decimated copy for the 3D preview: geometry only, never the input. + + Under the face budget decimate_mesh hands back its input unchanged - the + process-wide preview cache and every session's state then held the whole + object, metadata and cached properties included. + """ + small = decimate_mesh(mesh, face_count) + return trimesh.Trimesh(vertices=small.vertices.copy(), faces=small.faces.copy(), process=False) + + +def load_preview_mesh(data: bytes, scale: float, name: str) -> trimesh.Trimesh: + """Loads an uploaded STL, decimated for the instant preview. + + Raises ValueError naming the file if it holds no triangles (same loader as + the pipeline, so preview and run reject the same files). + """ + mesh = inlayer.load_mesh(io.BytesIO(data), name, file_type="stl") if scale != 1.0: mesh.apply_scale(scale) return decimate_mesh(mesh, PREVIEW_FACE_BUDGET) diff --git a/i18n.py b/i18n.py index 21ce300..3eaa6ba 100644 --- a/i18n.py +++ b/i18n.py @@ -78,6 +78,12 @@ def get_language() -> str: return _current.get() +def format_int(n: int) -> str: + """Integer with the current language's thousands separator (12,345 / 12.345).""" + text = f"{n:,}" + return text.replace(",", ".") if get_language() == "de" else text + + def t(key: str, /, **kwargs: object) -> str: """Uebersetzt `key` in die aktuelle Sprache und fuellt Platzhalter. @@ -474,13 +480,9 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Schritt 2/4: Toleranz-Offset...", "en": "Step 2/4: tolerance offset...", }, - "app.progress.step2b": { - "de": "Schritt 2b/4: {n} Figuren anordnen...", - "en": "Step 2b/4: arranging {n} figures...", - }, "app.progress.step3": { - "de": "Schritt 3/4: Inlay konstruieren...", - "en": "Step 3/4: constructing inlay...", + "de": "Schritt 3/4: Figuren anordnen, Inlay konstruieren...", + "en": "Step 3/4: arranging figures, constructing inlay...", }, "app.progress.step4": { "de": "Schritt 4/4: Wandstärkenprüfung...", @@ -506,13 +508,9 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Berechne Toleranz-Offset (Voxel-Dilation)...", "en": "Computing tolerance offset (voxel dilation)...", }, - "app.log.arrange": { - "de": "Ordne {n} Figuren stabil an (gap={gap} mm, style={style})...", - "en": "Arranging {n} figures on a stable grid (gap={gap} mm, style={style})...", - }, "app.log.build": { - "de": "Konstruiere Inlay (CSG Boolean)...", - "en": "Constructing inlay (CSG boolean)...", + "de": "Ordne Figuren an und konstruiere das Inlay (CSG Boolean)...", + "en": "Arranging figures and constructing the inlay (CSG boolean)...", }, "app.log.wall_check": { "de": "Führe 3D-Wandstärkenprüfung durch...", @@ -532,16 +530,12 @@ def t(key: str, /, **kwargs: object) -> str: "en": "🟢 Wall thickness OK", }, "app.results.wall_thin": { - "de": "⚠️ Wandstärke zu dünn", - "en": "⚠️ Wall too thin", + "de": "⚠️ Prüfung nicht bestanden", + "en": "⚠️ Check failed", }, "app.results.wall_warning": { - "de": "Mindestwandstärke von {wall} mm wird an Stellen unterschritten (gemessen: {measured} mm)!{affected}", - "en": "The minimum wall thickness of {wall} mm is not met in places (measured: {measured} mm)!{affected}", - }, - "app.results.affected": { - "de": "\n\nBetroffene Figur(en): **{names}**", - "en": "\n\nAffected figure(s): **{names}**", + "de": "Das Inlay erfüllt die Vorgaben nicht (Mindestwandstärke {wall} mm):\n\n{findings}", + "en": "The inlay does not meet the targets (minimum wall thickness {wall} mm):\n\n{findings}", }, "app.metric.min_wall": { "de": "Min Wandstärke", @@ -738,12 +732,12 @@ def t(key: str, /, **kwargs: object) -> str: "en": " Result: {faces} triangles", }, "pipeline.wall_verify": { - "de": "Berechne 3D-Wandstärken-Verifikation (Distanz zu den Box-Wänden) ...", - "en": "Computing 3D wall thickness verification (distance to the box walls) ...", + "de": "Wandstärken-Prüfung (gemessen an den Aussparungen) ...", + "en": "Wall check (measured on the cavities) ...", }, "pipeline.min_wall": { - "de": " Mindest-Wandstärke (Box-Wände): {measured} mm (Ziel >= {target} mm)", - "en": " Minimum wall thickness (box walls): {measured} mm (target >= {target} mm)", + "de": " Dünnste Seiten-/Bodenwand: {measured} mm (Ziel >= {target} mm)", + "en": " Thinnest side/floor wall: {measured} mm (target >= {target} mm)", }, "config.bad_finger_axis": { "de": "finger_recess_axis muss 'x' oder 'y' sein (ist '{value}')", @@ -773,6 +767,46 @@ def t(key: str, /, **kwargs: object) -> str: "de": "CSG-Differenz ergab leeres Mesh. Prüfe Box-Dimensionen und ob sich die Geometrien überlappen.", "en": "CSG difference produced an empty mesh. Check the box dimensions and whether the geometries overlap.", }, + "error.no_wall_check": { + "de": "Dieses Mesh trägt keine Wandstärken-Prüfung – sie entsteht in build_inlay.", + "en": "This mesh carries no wall check – build_inlay creates it.", + }, + "check.side": { + "de": "{name}: Seitenwand {measured} mm (Ziel {target} mm)", + "en": "{name}: side wall {measured} mm (target {target} mm)", + }, + "check.floor": { + "de": "{name}: Boden {measured} mm (Ziel {target} mm)", + "en": "{name}: floor {measured} mm (target {target} mm)", + }, + "check.inner": { + "de": "{name}: Wand zu {other} nur {measured} mm (Ziel {target} mm)", + "en": "{name}: wall to {other} only {measured} mm (target {target} mm)", + }, + "check.merged": { + "de": "{name}: Aussparung verschmilzt mit {other} (Ziel {target} mm Abstand)", + "en": "{name}: cavity merges with {other} (target {target} mm apart)", + }, + "check.sealed": { + "de": "{name}: Aussparung ist nach oben geschlossen – ein Hohlraum im Druck", + "en": "{name}: cavity is closed at the top – a sealed void in the print", + }, + "check.no_cavity": { + "de": "{name}: keine Aussparung – die Figur liegt außerhalb der Box", + "en": "{name}: no cavity – the figure lies outside the box", + }, + "error.input_not_found": { + "de": "Eingabedatei nicht gefunden: {path}", + "en": "Input file not found: {path}", + }, + "error.empty_input": { + "de": "{name} enthält keine Dreiecke – die Datei ist leer oder keine gültige STL.", + "en": "{name} contains no triangles – the file is empty or not a valid STL.", + }, + "error.grid_too_large": { + "de": "{name} ist für diese Auflösung zu groß: das Voxelgitter hätte {voxels} Voxel (Grenze {limit}). Wähle einen größeren voxel_pitch oder prüfe die Skalierung.", + "en": "{name} is too large for this resolution: its voxel grid would have {voxels} voxels (limit {limit}). Choose a larger voxel_pitch or check the scale.", + }, # --- CLI ---------------------------------------------------------------- "cli.description": { "de": "Inlayer: Erstellt 3D-druckbare Verpackungseinleger für Figuren.", @@ -902,13 +936,9 @@ def t(key: str, /, **kwargs: object) -> str: "de": "[2/4] Toleranz-Offset berechnen", "en": "[2/4] Computing tolerance offset", }, - "cli.step2b": { - "de": "[2b/4] {n} Figuren anordnen (gap={gap} mm, style={style})", - "en": "[2b/4] Arranging {n} figures (gap={gap} mm, style={style})", - }, "cli.step3": { - "de": "[3/4] Inlay konstruieren", - "en": "[3/4] Constructing inlay", + "de": "[3/4] Figuren anordnen und Inlay konstruieren", + "en": "[3/4] Arranging figures and constructing the inlay", }, "cli.saved": { "de": " => {path} gespeichert", @@ -926,6 +956,14 @@ def t(key: str, /, **kwargs: object) -> str: "de": "Erfolg: Mindestwandstärke von {wall} mm wird überall eingehalten!", "en": "Success: the minimum wall thickness of {wall} mm is met everywhere!", }, + "cli.check_failed": { + "de": "Prüfung nicht bestanden – {path} wurde trotzdem geschrieben, damit du es ansehen kannst (Exit-Code {code}).", + "en": "Check failed – {path} was written anyway so you can inspect it (exit code {code}).", + }, + "cli.recess_position_ignored": { + "de": "Hinweis: --finger-recess-position wird ohne --finger-recesses ignoriert.", + "en": "Note: --finger-recess-position is ignored without --finger-recesses.", + }, "cli.total_time": { "de": "Gesamtlaufzeit: {seconds}s", "en": "Total runtime: {seconds}s", @@ -943,6 +981,22 @@ def t(key: str, /, **kwargs: object) -> str: "de": "{name} muss > 0 sein (ist {value})", "en": "{name} must be > 0 (is {value})", }, + "config.must_be_non_negative": { + "de": "{name} muss >= 0 sein (ist {value})", + "en": "{name} must be >= 0 (is {value})", + }, + "config.must_be_finite": { + "de": "{name} muss eine endliche Zahl sein (ist {value})", + "en": "{name} must be a finite number (is {value})", + }, + "config.must_be_fraction": { + "de": "{name} muss > 0 und <= 1 sein (ist {value})", + "en": "{name} must be > 0 and <= 1 (is {value})", + }, + "config.must_be_at_least": { + "de": "{name} muss >= {minimum} sein (ist {value})", + "en": "{name} must be >= {minimum} (is {value})", + }, "config.bad_box_shape": { "de": "box_shape muss 'box' oder 'cylinder' sein (ist '{value}')", "en": "box_shape must be 'box' or 'cylinder' (is '{value}')", diff --git a/inlayer.py b/inlayer.py index 2619a73..9aa35ec 100644 --- a/inlayer.py +++ b/inlayer.py @@ -30,8 +30,9 @@ # Uebersetzungsfunktion laeuft deshalb unter dem Alias `t_`. from i18n import t as t_ from concurrent.futures import ThreadPoolExecutor -from dataclasses import dataclass +from dataclasses import dataclass, fields from typing import Callable, Final, Any, Iterable, TypeVar, cast +from manifold3d import Manifold, Mesh, OpType from scipy.ndimage import ( binary_closing, binary_dilation, @@ -48,9 +49,30 @@ pass +def _positive(value: float) -> bool: + return value > 0 + + +def _non_negative(value: float) -> bool: + return value >= 0 + + +# Which fields must be > 0 and which >= 0 (None - "automatic" - is always +# fine). A table so that a new field cannot silently skip its check, and so +# each rule has exactly one message: "-c -0.5" used to say "must be > 0" +# although 0 is allowed. +_RANGE_RULES: Final = ( + (_positive, ("wall_thickness", "voxel_pitch", "stl_unit_to_mm", "finger_radius", + "box_width", "box_depth", "box_height", "box_diameter", "figure_gap")), + (_non_negative, ("clearance", "finger_recess_z_offset")), +) +_RANGE_MESSAGES: Final = {_positive: "config.must_be_positive", + _non_negative: "config.must_be_non_negative"} + + @dataclass(frozen=True) class Config: - """Laufzeit-Konfiguration für die Inlayer-Pipeline.""" + """Runtime configuration of the Inlayer pipeline.""" clearance: float = 0.4 wall_thickness: float = 2.0 @@ -82,60 +104,45 @@ class Config: enable_parallel: bool = False def __post_init__(self) -> None: - """Validiert Parameter-Bereiche, damit Fehler früh sichtbar werden.""" - if self.finger_radius <= 0: - raise ValueError(t_("config.must_be_positive", name="finger_radius", value=self.finger_radius)) - if self.finger_recess_axis not in ("x", "y"): - raise ValueError( - t_("config.bad_finger_axis", value=self.finger_recess_axis) - ) - if self.finger_recess_z_offset < 0: - raise ValueError( - t_("config.must_be_positive", name="finger_recess_z_offset", value=self.finger_recess_z_offset) - ) - if not -1.0 <= self.finger_recess_position <= 1.0: - raise ValueError( - t_("config.bad_finger_position", value=self.finger_recess_position) - ) - if self.clearance < 0: - raise ValueError(t_("config.must_be_positive", name="clearance", value=self.clearance)) - if self.wall_thickness <= 0: - raise ValueError(t_("config.must_be_positive", name="wall_thickness", value=self.wall_thickness)) + """Validates every value range, so mistakes surface here and not as an + unrelated error deep inside the pipeline.""" + # NaN and inf pass every `<` comparison below: -w nan ended in "CSG + # difference failed", -c nan in "cannot convert float NaN to integer". + for field in fields(self): + value = getattr(self, field.name) + if isinstance(value, float) and not math.isfinite(value): + raise ValueError(t_("config.must_be_finite", name=field.name, value=value)) + for rule, names in _RANGE_RULES: + for name in names: + value = getattr(self, name) + if value is not None and not rule(value): + raise ValueError(t_(_RANGE_MESSAGES[rule], name=name, value=value)) if not 0.0 < self.depth_fraction <= 1.0: - raise ValueError( - t_("config.must_be_positive", name="depth_fraction", value=self.depth_fraction) - ) - if self.voxel_pitch <= 0: - raise ValueError(t_("config.must_be_positive", name="voxel_pitch", value=self.voxel_pitch)) + raise ValueError(t_("config.must_be_fraction", name="depth_fraction", + value=self.depth_fraction)) if self.decimate_faces < 4: - raise ValueError( - t_("config.must_be_positive", name="decimate_faces", value=self.decimate_faces) - ) - if self.stl_unit_to_mm <= 0: - raise ValueError( - t_("config.must_be_positive", name="stl_unit_to_mm", value=self.stl_unit_to_mm) - ) - for name, val in ( - ("box_width", self.box_width), - ("box_depth", self.box_depth), - ("box_height", self.box_height), - ("box_diameter", self.box_diameter), - ("figure_gap", self.figure_gap), - ): - if val is not None and val <= 0: - raise ValueError(t_("config.must_be_positive", name=name, value=val)) + raise ValueError(t_("config.must_be_at_least", name="decimate_faces", + value=self.decimate_faces, minimum=4)) + if not -1.0 <= self.finger_recess_position <= 1.0: + raise ValueError(t_("config.bad_finger_position", value=self.finger_recess_position)) + if self.finger_recess_axis not in ("x", "y"): + raise ValueError(t_("config.bad_finger_axis", value=self.finger_recess_axis)) if self.box_shape not in ("box", "cylinder"): - raise ValueError( - t_("config.bad_box_shape", value=self.box_shape) - ) + raise ValueError(t_("config.bad_box_shape", value=self.box_shape)) if self.layout_style not in ("compact", "horizontal", "vertical"): - raise ValueError( - t_("config.bad_layout_style", value=self.layout_style) - ) + raise ValueError(t_("config.bad_layout_style", value=self.layout_style)) + + @property + def effective_figure_gap(self) -> float: + """The wall between two cavities: figure_gap, or the wall thickness.""" + return self.wall_thickness if self.figure_gap is None else self.figure_gap _DEFAULT_CFG: Final = Config() +# Input read when the CLI gets no -i (and the web app no upload) +DEFAULT_INPUT: Final[str] = "figure.stl" + def _log(msg: str, t0: float | None = None) -> float: """Gibt eine Statuszeile mit optionaler Laufzeit seit t0 aus.""" @@ -167,6 +174,26 @@ def _log(msg: str, t0: float | None = None) -> float: FINGER_BAND_VOXELS: Final[float] = 5.0 FINGER_BAND_MIN_MM: Final[float] = 2.0 +# Resolution of the revolved recess template (quarter-circle profile, turns) +RECESS_ARC_SEGMENTS: Final[int] = 16 +RECESS_SECTIONS: Final[int] = 64 + +# --- Box and wall check ----------------------------------------------------- + +# Every cutter (figure cavity, recess shaft) ends this far above the box's top +# face. Ending exactly on the face would hand the boolean coplanar faces, +# ending below it leaves a sealed void. Larger than any sensible voxel_pitch; +# it cuts only air, so the value does not show in the result. +CUT_OVERSHOOT_MM: Final[float] = 1.0 + +# The wall check measures the real meshes (float32 inside manifold3d), not a +# voxel grid, so its tolerance only has to absorb rounding and the cylinder's +# chord error (< 0.02 mm at ~1 mm segments). +WALL_TOLERANCE_MM: Final[float] = 0.05 + +# Below this a clipped cutter counts as empty (boolean slivers, not pockets) +_MIN_VOLUME_MM3: Final[float] = 1e-3 + _T = TypeVar("_T") _R = TypeVar("_R") @@ -177,14 +204,17 @@ def _effective_workers(n_items: int) -> int: def _parallel_map( - fn: Callable[[_T], _R], items: Iterable[_T], config: Config, what: str = "" + fn: Callable[[_T], _R], items: Iterable[_T], config: Config, what: str = "", + worker_init: Callable[[], None] | None = None, ) -> list[_R]: - """Wendet fn auf alle Items an – per ThreadPool, falls enable_parallel gesetzt. - - numpy/scipy/trimesh geben den GIL waehrend ihrer C-Aufrufe frei, daher - bringen Threads hier echten Multi-Core-Speedup ohne Pickling-Overhead. - Die Ergebnis-Reihenfolge entspricht der Item-Reihenfolge; Exceptions aus - den Workern werden unveraendert weitergereicht. + """Applies fn to every item - in a thread pool if enable_parallel is set. + + numpy/scipy/trimesh release the GIL during their C calls, so threads give + a real multi-core speedup without pickling. Results keep the item order; + exceptions from the workers propagate unchanged. `worker_init` runs in + each worker before fn (the web app attaches Streamlit's ScriptRunContext + there) - the one thread pool of both entry points, so neither can forget + the language hand-over below. """ item_list = list(items) if not config.enable_parallel or len(item_list) < 2: @@ -195,13 +225,15 @@ def _parallel_map( n=len(item_list), workers=workers) ) - # ThreadPoolExecutor-Worker starten mit einem frischen Kontext und sehen die - # per ContextVar gesetzte Sprache nicht. Sie wird deshalb eingefangen und im - # Worker erneut gesetzt, sonst loggen die Threads in der Standardsprache. + # ThreadPoolExecutor workers start with a fresh context and do not see the + # language set through the ContextVar. It is captured here and set again + # inside each worker, otherwise the threads log in the default language. lang = i18n.get_language() def _with_lang(item: _T) -> _R: i18n.set_language(lang) + if worker_init is not None: + worker_init() return fn(item) with ThreadPoolExecutor(max_workers=workers) as ex: @@ -288,31 +320,141 @@ def apply_euler_rotation( return m +def load_mesh(source: Any, name: str, file_type: str | None = None) -> trimesh.Trimesh: + """Loads a file (path or file object) as a single mesh. + + trimesh does not raise on an empty or garbled STL - it returns a mesh + without triangles, and the pipeline then fails far away with a cryptic + 'NoneType' error. Uploads are untrusted input, so any file that yields no + triangles is rejected here with a message that names it. + """ + try: + mesh = trimesh.load(source, file_type=file_type, force="mesh") + except Exception as exc: + raise ValueError(t_("error.empty_input", name=name)) from exc + if not isinstance(mesh, trimesh.Trimesh) or len(mesh.faces) == 0: + raise ValueError(t_("error.empty_input", name=name)) + return mesh + + +# Upper bound for a single voxel grid. The finest grid in the pipeline is +# dilate's (voxel_pitch / 2); a boolean grid costs one byte per voxel and +# scipy's morphology holds several copies of it. Without the bound a small +# upload scaled up (or a tiny STL with a huge bounding box) takes down a shared +# web-app container instead of failing with a message. +MAX_GRID_VOXELS: Final[int] = 1_000_000_000 + +# Sample spacing of `_voxelize_surface`, as a fraction of the pitch. Samples +# on a row lie this far apart, rows as well, so the nearest neighbour of any +# sample is at most sqrt(0.4² + 0.2²) = 0.45 pitch away. Below 0.5 pitch per +# coordinate, neighbouring samples round into the same or adjacent voxels: the +# voxel shell stays closed and fill() cannot leak - the same guarantee trimesh's +# subdivision voxelizer gives with its pitch / 2 edge limit. +_SURFACE_SAMPLE_SPACING: Final[float] = 0.4 + + +def _check_grid_size(extents: np.ndarray, pitch: float, name: str) -> None: + """Refuses a figure whose voxel grid at `pitch` would exceed MAX_GRID_VOXELS.""" + voxels = float(np.prod(np.ceil(np.asarray(extents) / pitch) + 1)) + if voxels > MAX_GRID_VOXELS: + raise ValueError(t_("error.grid_too_large", name=name, voxels=f"{voxels:.1e}", + limit=f"{MAX_GRID_VOXELS:.1e}")) + + +def _lerp(p: np.ndarray, r: np.ndarray, t: np.ndarray) -> np.ndarray: + """p + t (r - p), exact at t = 0, at t = 1 and on axes where p and r agree. + + Voxel indices come from rounding, and a face lying exactly on a voxel + boundary (a 10 mm cube at pitch 0.4) sits on the .5 of that rounding: one + ulp of interpolation error there flips a whole layer of voxels. + """ + return np.where(t == 1.0, r, p + t * (r - p)) + + +def _segment_points(p0: np.ndarray, p1: np.ndarray, spacing: float) -> np.ndarray: + """Evenly spaced points on each segment p0[i]-p1[i], endpoints included.""" + count = np.ceil(np.linalg.norm(p1 - p0, axis=1) / spacing).astype(np.int64) + 1 + seg = np.repeat(np.arange(len(p0)), count) + step = np.arange(len(seg)) - np.repeat(np.cumsum(count) - count, count) + q = step / np.maximum(count[seg] - 1, 1) + return _lerp(p0[seg], p1[seg], q[:, None]) + + +def _voxelize_surface(mesh: trimesh.Trimesh, pitch: float) -> Any: + """Surface voxelization whose cost grows with area, not with edge length². + + trimesh's voxelizer quarters every triangle until *all* its edges are + shorter than pitch / 2: a long, thin triangle (CAD exports of rods, pins, + profiles) costs (length / pitch)² sub-triangles however little area it has. + A 256-triangle rod of 40 mm took 1.95 GB, a 12-triangle 250 mm bar aborted + with "max_iter exceeded". Here each triangle is sampled in rows parallel to + its longest edge instead, plus its three edges; see _SURFACE_SAMPLE_SPACING + for why the shell stays closed. Only for raw input meshes - the later steps + voxelize marching-cubes output whose edges are about one pitch long. + """ + tri = mesh.triangles + n = len(tri) + spacing = _SURFACE_SAMPLE_SPACING * pitch + lengths = np.linalg.norm(np.roll(tri, -1, axis=1) - tri, axis=2) + # Rotate every triangle so that a-b is its longest edge: the apex c then + # projects onto a-b, so every row parallel to a-b stays inside the triangle. + order = (lengths.argmax(axis=1)[:, None] + np.arange(3)) % 3 + a, b, c = (tri[np.arange(n), order[:, k]] for k in range(3)) + longest = lengths.max(axis=1) + height = np.linalg.norm(np.cross(b - a, c - a), axis=1) / np.maximum(longest, 1e-12) + + n_rows = np.ceil(height / spacing).astype(np.int64) + 1 + row_tri = np.repeat(np.arange(n), n_rows) + row = np.arange(len(row_tri)) - np.repeat(np.cumsum(n_rows) - n_rows, n_rows) + s = (row / np.maximum(n_rows[row_tri] - 1, 1))[:, None] + ra, rb, rc = a[row_tri], b[row_tri], c[row_tri] + points = np.concatenate([ + _segment_points(_lerp(ra, rc, s), _lerp(rb, rc, s), spacing), + _segment_points(b, c, spacing), + _segment_points(c, a, spacing), + ]) + + # Same rounding as trimesh.voxel.creation.voxelize_subdivide + hit = np.round(points / pitch).astype(np.int64) + origin = hit.min(axis=0) + matrix = np.zeros(hit.max(axis=0) - origin + 1, dtype=bool) + matrix[tuple((hit - origin).T)] = True + transform = trimesh.transformations.scale_and_translate( + scale=pitch, translate=origin * pitch + ) + return cast(Any, trimesh.voxel.VoxelGrid)(matrix, transform=transform) + + def prepare_figure(path: str, config: Config = _DEFAULT_CFG) -> trimesh.Trimesh: - """Lädt, repariert, dezimiert und glättet die Eingabefigur.""" + """Loads, repairs, decimates and smooths an input figure.""" if not os.path.isfile(path): - raise FileNotFoundError(f"Eingabedatei nicht gefunden: {path}") + raise FileNotFoundError(t_("error.input_not_found", path=path)) t = time.perf_counter() _log(t_("pipeline.load", path=path)) - m = cast(trimesh.Trimesh, trimesh.load(path, force="mesh")) + m = load_mesh(path, name=path) if config.stl_unit_to_mm != 1.0: m.apply_scale(config.stl_unit_to_mm) _log(t_("pipeline.loaded", faces=f"{len(m.faces):,}", extents=m.extents.round(2)), t) - - # Reparatur nur, wenn sie etwas zu tun hat. pymeshfix ist der teuerste - # Einzelschritt vor der Voxelisierung (gemessen ~30 % von prepare_figure bei - # 82k Dreiecken) und laesst ein bereits wasserdichtes, konsistent gewickeltes - # Mesh unveraendert. Self-Intersections deckt der Test nicht ab, die loest - # aber ohnehin die nachfolgende Voxelisierung auf — sie rastert Dreiecke und - # kennt keine Topologie. Entscheidend ist Wasserdichtheit: daran haengt, ob - # vox.fill() den Innenraum trifft statt nach aussen zu laufen. + _check_grid_size(m.extents, config.voxel_pitch / 2, name=path) + + # Repair only when there is something to repair. pymeshfix is the most + # expensive single step before voxelization (measured ~30 % of + # prepare_figure at 82k triangles) and leaves a watertight, consistently + # wound mesh unchanged. Self-intersections are not covered by the test, but + # the voxelization resolves them anyway - it rasterizes triangles and knows + # no topology. Watertightness is what matters: it decides whether vox.fill() + # hits the interior instead of running outwards. t = _log(t_("pipeline.repair")) if m.is_watertight and m.is_winding_consistent: _log(t_("pipeline.repair_skipped", faces=f"{len(m.faces):,}"), t) else: mf = pymeshfix.MeshFix(m.vertices, m.faces) - mf.repair() + # pymeshfix's default removes every shell but the one with the most + # triangles: a miniature with a separate base lost the base, and a + # holed body next to an intact small part lost the *body*. Whether a + # part survived depended on an unrelated hole anywhere in the file. + mf.repair(remove_smallest_components=False) m = trimesh.Trimesh(vertices=mf.points, faces=mf.faces) _log(t_("pipeline.repaired", faces=f"{len(m.faces):,}"), t) @@ -325,12 +467,12 @@ def prepare_figure(path: str, config: Config = _DEFAULT_CFG) -> trimesh.Trimesh: _log(t_("pipeline.decimate_skipped", faces=f"{current_faces:,}"), t) t = _log(t_("pipeline.voxelize_closing")) - vox = cast(Any, m.voxelized(pitch=config.voxel_pitch)) + vox = _voxelize_surface(m, config.voxel_pitch) vox.fill() - # Padding um die Closing-Iterationen: ohne Rand wird die Dilation an den - # Array-Grenzen geclippt und die anschliessende Erosion schrumpft die Figur - # an ihren Extrempunkten um bis zu 'iters' Voxel (analog zu dilate). + # Pad by the closing iterations: without a border the dilation is clipped + # at the array edges and the following erosion shrinks the figure at its + # extreme points by up to 'iters' voxels (same as in dilate). iters = 2 padded = np.pad(vox.matrix, iters, constant_values=False) closed = binary_closing(padded, iterations=iters) @@ -341,39 +483,48 @@ def prepare_figure(path: str, config: Config = _DEFAULT_CFG) -> trimesh.Trimesh: return m -def _dilation_steps(distance: float, config: Config) -> tuple[int, float]: - """Dilations-Iterationen und tatsaechlicher Zuwachs pro Seite fuer `dilate`. +def _dilation_iterations(distance: float, config: Config) -> int: + """Number of dilation steps `dilate` needs for `distance`. - Inflation: voxel_pitch/2 aus prepare_figure + pitch/2 aus der Rekonstruktion - in dilate. floor(x + 0.5) statt round(): Banker's Rounding wuerde den - Default-Fall (clearance=0.4, pitch=0.4 -> x=0.5) auf 0 abrunden. Das - 1e-9-Epsilon faengt ab, dass dieser Fall ((0.4 - 0.3) / 0.2) durch - Float-Rundung knapp unter 0.5 landet. + Inflation: voxel_pitch/2 from prepare_figure + pitch/2 from the + reconstruction in dilate (pitch = voxel_pitch/2). floor(x + 0.5) instead + of round(): banker's rounding would round the default case (clearance 0.4, + pitch 0.4 -> x = 0.5) down to 0. The 1e-9 epsilon catches that this case + ((0.4 - 0.3) / 0.2) lands just below 0.5 through float rounding. - Der Zuwachs ist nicht `distance`: die Dilation ist auf `pitch` quantisiert - und die eigene Marching-Cubes-Rekonstruktion traegt nochmals pitch/2 auf. - Gemessen (Wuerfel und Kugel identisch, 2026-08) trifft - `iters * pitch + pitch / 2` den realen Bounding-Box-Zuwachs exakt. Wer den - Abstand zwischen dilatierten Figuren garantieren muss (siehe - `arrange_with_stable_bounds`), rechnet damit statt mit clearance. + The resulting growth per side is not `distance` but, measured (cube and + sphere alike, 2026-08), `iters * pitch + pitch / 2` - the dilation is + quantized to `pitch` and its own marching cubes adds pitch/2. Nothing + relies on that number any more: build_inlay measures the real cavities. """ pitch = config.voxel_pitch / 2 inflation = config.voxel_pitch / 2 + pitch / 2 - iters = max(0, math.floor((distance - inflation) / pitch + 0.5 + 1e-9)) - return iters, iters * pitch + pitch / 2 + return max(0, math.floor((distance - inflation) / pitch + 0.5 + 1e-9)) + + +# Share of dilation steps done with the full 3x3x3 cube instead of the +# 6-neighbourhood cross. k steps of a cross and m of a cube grow a surface with +# normal u by (k - m) * max|u_i| + m * sum|u_i| voxels (the support functions of +# octahedron and cube). Along an axis that is k either way; along the space +# diagonal it is k exactly for m / k = (sqrt(3) - 1) / 2. Every other direction +# then lies within 0.97 ... 1.06 of the axis growth - with the cross alone the +# diagonal got 0.58 of it, alternating 1:1 overshoots by 15 %. +_CUBE_STEP_SHARE: Final[float] = (math.sqrt(3.0) - 1.0) / 2.0 +_CUBE: Final = np.ones((3, 3, 3), dtype=bool) def dilate( mesh: trimesh.Trimesh, distance: float, config: Config = _DEFAULT_CFG ) -> trimesh.Trimesh: - """Toleranz-Offset via Voxel-Dilation (robuster als Normalen-Shift). - - Kompensiert die systematische Inflation der Voxel-Pipeline: die - Marching-Cubes-Rekonstruktion in prepare_figure traegt ~voxel_pitch/2 pro - Seite auf, die hiesige ~pitch/2. Gemessen (Wuerfel und Kugel identisch) lag - das effektive Spiel ohne Kompensation um 0.75 * voxel_pitch ueber der - konfigurierten clearance. Kehrseite: das effektive Spiel kann nicht unter - ~0.75 * voxel_pitch fallen (iters >= 0). + """Tolerance offset via voxel dilation (more robust than a normal shift). + + Compensates the systematic inflation of the voxel pipeline: the + marching-cubes reconstruction in prepare_figure adds ~voxel_pitch/2 per + side, the one here ~pitch/2. Measured (cube and sphere alike), the + effective clearance without compensation was 0.75 * voxel_pitch above the + configured one. Flip side: it cannot drop below ~0.75 * voxel_pitch + (iters >= 0). The dilation is close to isotropic, so slopes and curves get + the same clearance as axis-parallel faces (see _CUBE_STEP_SHARE). """ pitch = config.voxel_pitch / 2 t = _log(t_("pipeline.voxelize_dilation", pitch=pitch)) @@ -381,24 +532,30 @@ def dilate( vox.fill() _log(t_("pipeline.grid_ready"), t) - iters, _ = _dilation_steps(distance, config) + iters = _dilation_iterations(distance, config) if iters > 0: - # Einmaliges Padding um 'iters' auf allen Seiten + # Pad by 'iters' on every side: both structuring elements grow at most + # one voxel per axis and step, so nothing is clipped at the border. dilated = np.pad(vox.matrix, iters, constant_values=False) - - # Vektorisiert: scipy-ndimage mit iterations-Parameter statt Python-Schleife. - # Mathematisch äquivalent zur vorherigen Schleife (close+dilate pro Iteration), - # aber ~10–50× schneller (C-Loop). - dilated = binary_closing(dilated, iterations=iters) - dilated = binary_dilation(dilated, iterations=iters) + # scipy's default element (6-neighbourhood) grows an octahedron: 2 mm + # of clearance along the axes left 1.5 mm on a 45° slope. Some steps + # with the full 3x3x3 cube balance that - see _CUBE_STEP_SHARE. The + # growth along the axes, which _dilation_iterations is calibrated on, + # is one voxel per step either way. (No closing before the dilation: + # dilating a closing with the same element equals dilating the input - + # checked bit for bit on 200 random grids - and cost 2/3 of the time.) + cube_steps = round(iters * _CUBE_STEP_SHARE) + dilated = binary_dilation(dilated, iterations=iters - cube_steps) + if cube_steps: + dilated = binary_dilation(dilated, structure=_CUBE, iterations=cube_steps) else: - # Gewuenschtes Spiel <= systematische Inflation: keine Dilation. - # (scipy interpretiert iterations=0 als "bis Konvergenz", daher der Guard.) + # Requested clearance <= systematic inflation: no dilation. + # (scipy treats iterations=0 as "until convergence", hence the guard.) dilated = vox.matrix t = _log(t_("pipeline.marching_cubes")) - # iters=0 laesst den Transform unveraendert, daher ein Aufruf fuer beide Faelle. + # iters=0 leaves the transform unchanged, so one call serves both cases. result = _grid_to_mesh(dilated, _padded_transform(vox.transform, iters)) _log( t_("pipeline.result", faces=f"{len(result.faces):,}", extents=result.extents.round(2)), t @@ -406,754 +563,500 @@ def dilate( return result -def arrange_figures( - meshes: list[trimesh.Trimesh], +def arrange_footprints( + sizes: np.ndarray, gap: float, layout_style: str = "compact", - reference_meshes: list[trimesh.Trimesh] | None = None, - sorting_reference_meshes: list[trimesh.Trimesh] | None = None, + sort_keys: Iterable[float] | None = None, box_width: float | None = None, - finger_radius: float = 0.0, - finger_axis: str = "x", - outer_margin: float | None = None, -) -> list[trimesh.Trimesh]: - """Ordnet mehrere Meshes kollisionsfrei in der XY-Ebene an. - - layout_style kann sein: - - "compact": Shelf-Packing zeilenweise (Standard, absteigend nach Flaeche sortiert) - - "horizontal": Nebeneinander auf der X-Achse zentriert (Original-Reihenfolge) - - "vertical": Untereinander auf der Y-Achse zentriert (Original-Reihenfolge) - - `gap` ist der Abstand zwischen den Figuren, `outer_margin` das, was bei - manueller `box_width` je Seite ausserhalb des Layouts dazukommt (None -> - `gap`). Das sind zwei verschiedene Groessen: `arrange_with_stable_bounds` - schlaegt auf den Gap die Dilation auf und reicht als Rand die Summe aus - Wandstaerke und Bounds-Padding durch. + margin: float = 0.0, +) -> np.ndarray: + """Places rectangles in the XY plane without collisions. + + `sizes` holds one (width, depth) per figure - the footprint of everything + that is cut for it. Returns the position of each footprint's min corner, + `gap` apart from its neighbours: + - "compact": shelf packing, largest first (by `sort_keys`, default the + footprint area), rows up to a target width - `box_width` minus `margin` + on each side when the box width is fixed. + - "horizontal": side by side along X, smallest first, bottoms flush. + - "vertical": stacked along Y in the given order, centred in X. """ - if not meshes: + sizes = np.asarray(sizes, dtype=float).reshape(-1, 2) + n = len(sizes) + if n == 0: raise ValueError(t_("error.no_meshes")) - if len(meshes) == 1: - return [meshes[0].copy()] - - t = _log(t_("pipeline.arrange", n=len(meshes), gap=f"{gap:.1f}", style=layout_style)) - - # Bounding-Box-Groessen fuer das Layout ermitteln (Referenz-Meshes nutzen, falls vorhanden); - # entlang der Mulden-Achse beidseitig um finger_radius erweitert (Platz fuer Fingermulden) - ref_meshes = reference_meshes if reference_meshes is not None else meshes - axis = 0 if finger_axis == "x" else 1 - fr_pad = np.zeros(3) - fr_pad[axis] = 2.0 * finger_radius - sizes = [m.extents + fr_pad for m in ref_meshes] - - # Bounding-Box-Groessen fuer eine stabile Sortierung ermitteln (z.B. unrotierte Original-Modelle) - sort_ref_meshes = sorting_reference_meshes if sorting_reference_meshes is not None else ref_meshes - sort_sizes = [m.extents + fr_pad for m in sort_ref_meshes] + keys = sizes.prod(axis=1) if sort_keys is None else np.asarray(list(sort_keys), dtype=float) + positions = np.zeros((n, 2)) + if n == 1: + return positions + t = _log(t_("pipeline.arrange", n=n, gap=f"{gap:.1f}", style=layout_style)) if layout_style == "horizontal": - # Sortiere Indizes nach XY-Fläche aufsteigend (kleinstes zuerst) basierend auf der Sortier-Referenz - order = sorted( - range(len(meshes)), - key=lambda i: sort_sizes[i][0] * sort_sizes[i][1] - ) - - # Dict statt Liste mit None-Platzhaltern: der Rueckgabetyp bleibt - # list[Trimesh] ohne cast, und eine vergessene Zuweisung faellt beim - # Einsammeln als KeyError auf statt als None im Ergebnis. - placed: dict[int, trimesh.Trimesh] = {} - current_x = 0.0 - for idx in order: - m = meshes[idx] - m_copy = m.copy() - - # Nutze die Bounding Box des Referenz-Meshes für die Ausrichtung - ref_bmin = ref_meshes[idx].bounds[0].copy() - if finger_radius > 0.0: - ref_bmin[axis] -= finger_radius - ref_size = sizes[idx] - - # Unten bündig ausgerichtet in Y (Referenz auf Y = 0), sequentiell in X - m_copy.apply_translation([ - current_x - ref_bmin[0], - -ref_bmin[1], - 0.0 - ]) - current_x += ref_size[0] + gap - placed[idx] = m_copy - _log(t_("pipeline.arranged_horizontal", n=len(meshes)), t) - return [placed[i] for i in range(len(meshes))] - - elif layout_style == "vertical": - result_vertical = [] - current_y = 0.0 - for i, m in enumerate(meshes): - m_copy = m.copy() - bmin = m_copy.bounds[0].copy() - if finger_radius > 0.0: - bmin[axis] -= finger_radius - # Zentriert in X, sequentiell in Y - m_copy.apply_translation([ - -sizes[i][0] / 2 - bmin[0], - current_y - bmin[1], - 0.0 - ]) - current_y += sizes[i][1] + gap - result_vertical.append(m_copy) - _log(t_("pipeline.arranged_vertical", n=len(meshes)), t) - return result_vertical - + x = 0.0 + for i in sorted(range(n), key=lambda i: keys[i]): + positions[i] = (x, 0.0) + x += sizes[i][0] + gap + _log(t_("pipeline.arranged_horizontal", n=n), t) + return positions + if layout_style == "vertical": + y = 0.0 + for i in range(n): + positions[i] = (-sizes[i][0] / 2, y) + y += sizes[i][1] + gap + _log(t_("pipeline.arranged_vertical", n=n), t) + return positions + + # Rows are filled with the full footprints. Filling them with the bare + # figure widths and adding the finger recesses afterwards made a row of k + # figures 2 * (k - 1) * finger_radius wider than the box it was packed for. + if box_width is not None: + target = box_width - 2 * margin else: - # Standard: compact (Shelf-Packing) - # 1. Ermittle die un-dilatierten, un-expandierten Bounding-Boxen der Figuren - sizes_unexpanded = [m.extents for m in ref_meshes] - sort_sizes_unexpanded = [m.extents for m in sort_ref_meshes] - - # 2. Nach XY-Fläche absteigend sortieren basierend auf der un-expandierten Sortier-Referenz - order = sorted( - range(len(meshes)), - key=lambda i: sort_sizes_unexpanded[i][0] * sort_sizes_unexpanded[i][1], - reverse=True, - ) - - if box_width is not None: - # Nutze die manuelle Box-Breite abzüglich Rand und Fingermulden - margin = gap if outer_margin is None else outer_margin - # Fingermulden erweitern nur entlang ihrer Achse; bei "y" bleibt die - # X-Breite unveraendert. - fr_x = 2 * finger_radius if axis == 0 else 0.0 - target_width = max(sizes_unexpanded[order[0]][0], box_width - 2 * margin - fr_x) - else: - # Ziel-Breite für ein un-expandiertes halbwegs quadratisches Layout - total_area = sum(sizes_unexpanded[i][0] * sizes_unexpanded[i][1] for i in order) - target_width = math.sqrt(total_area) * 1.3 - target_width = max(target_width, sizes_unexpanded[order[0]][0]) - - # 3. Shelf-Packing: Reihen mit un-expandierten Breiten füllen, um die Reihenzuordnung zu bestimmen - shelves_assignment: list[list[int]] = [] - current_x = 0.0 - row_items: list[int] = [] - - for idx in order: - sx = sizes_unexpanded[idx][0] - - # Passt das un-expandierte Mesh noch in die aktuelle Reihe? - if row_items and (current_x + sx) > target_width: - shelves_assignment.append(row_items) - current_x = 0.0 - row_items = [] - - row_items.append(idx) - current_x += sx + gap - - if row_items: - shelves_assignment.append(row_items) - - # 4. Nun die Zuweisung in die realen (mit finger_radius expandierten) Koordinaten übersetzen - packed: dict[int, trimesh.Trimesh] = {} - current_y = 0.0 - for row in shelves_assignment: - current_x = 0.0 - shelf_height = 0.0 - for idx in row: - sx, sy = sizes[idx][0], sizes[idx][1] - m = meshes[idx].copy() - bmin = m.bounds[0].copy() - if finger_radius > 0.0: - bmin[axis] -= finger_radius - - # Verschiebe an die reale X- und Y-Position - m.apply_translation([current_x - bmin[0], current_y - bmin[1], 0.0]) - packed[idx] = m - - current_x += sx + gap - shelf_height = max(shelf_height, sy) - - current_y += shelf_height + gap - - _log( - t_("pipeline.shelves", n=len(meshes), rows=len(shelves_assignment)), t - ) - return [packed[i] for i in range(len(meshes))] + target = max(math.sqrt(float(sizes.prod(axis=1).sum())) * 1.3, float(sizes[:, 0].max())) + rows: list[list[int]] = [[]] + x = 0.0 + for i in sorted(range(n), key=lambda i: keys[i], reverse=True): + if rows[-1] and x + sizes[i][0] > target: + rows.append([]) + x = 0.0 + rows[-1].append(i) + x += sizes[i][0] + gap + y = 0.0 + for row in rows: + x = 0.0 + for i in row: + positions[i] = (x, y) + x += sizes[i][0] + gap + y += max(sizes[i][1] for i in row) + gap + _log(t_("pipeline.shelves", n=n, rows=len(rows)), t) + return positions +def _is_manifold(m: trimesh.Trimesh) -> bool: + """True for a watertight mesh with at least one face.""" + return m.is_watertight and len(m.faces) > 0 -def arrange_with_stable_bounds( - reference: list[trimesh.Trimesh], - rotated: list[trimesh.Trimesh], - dilated: list[trimesh.Trimesh], - config: Config = _DEFAULT_CFG, -) -> tuple[list[trimesh.Trimesh], tuple[np.ndarray, np.ndarray], list[np.ndarray]]: - """Ordnet dilatierte Figuren auf einem stabilen Slot-Gitter an. - - Das Slot-Gitter wird aus den Referenz-Meshes berechnet und die dilatierten - (ggf. rotierten) Figuren werden an den Slot-Zentren platziert (nur XY, - Z bleibt unveraendert). Die Web-App uebergibt als Referenz die unrotierten - Figuren, damit die Slots bei Rotationsaenderungen stabil bleiben; die CLI - uebergibt die rotierten (Rotation steht dort fix). - - Der Slot-Abstand ist der konfigurierte figure_gap plus dem doppelten - Dilations-Zuwachs, damit die dilatierten Figuren den konfigurierten Abstand - tatsaechlich einhalten. - - Stabil sind die *Slots*, nicht die Box: die zurueckgegebenen Bounds - umschliessen immer die real angeordneten Figuren. Nur so passt die Box auch - dann, wenn eine Rotation die Figur groesser macht als ihre unrotierte - Referenz. - - Liefert (angeordnete dilatierte Meshes, Bounds fuer build_inlay, - XY-Translationen je Figur). Die Bounds sind in XY um - clearance + voxel_pitch (Voxel-Diskretisierungs-Ausgleich), in Z um - voxel_pitch/2 je Seite (Solidify-Inflation) und bei aktivierten - Fingermulden um finger_radius in X erweitert. - """ - fr = config.finger_radius if config.enable_finger_recesses else 0.0 - if len(reference) == 1: - bmin = reference[0].bounds[0] - bmax = reference[0].bounds[1] - # Kopieren wie im Multi-Pfad: der Aufrufer reicht ggf. gecachte Meshes - # herein, die niemand ueber diesen Rueckgabewert veraendern koennen soll. - arranged = [d.copy() for d in dilated] - translations = [np.zeros(2)] - else: - gap = config.figure_gap if config.figure_gap is not None else config.wall_thickness - # Die dilatierten Figuren sind pro Seite um den Dilations-Zuwachs dicker - # als die Referenz. Damit der konfigurierte Abstand nach der Dilation - # erhalten bleibt, wird der Slot-Abstand um 2*Zuwachs vergroessert. - # Nicht clearance verwenden: dilate quantisiert auf voxel_pitch/2 und hat - # eine Untergrenze, der reale Zuwachs weicht in beide Richtungen ab. - _, growth = _dilation_steps(config.clearance, config) - layout_gap = gap + 2.0 * growth - # Rand je Seite bei manueller Box-Breite: die Aussenwand aus build_inlay - # plus das Padding, das unten auf die stabilen Bounds geht. Frueher stand - # hier der Gap — das unterschlug das Padding und die Box lief ueber. - outer_margin = config.wall_thickness + config.clearance + config.voxel_pitch - layout = arrange_figures( - reference, layout_gap, config.layout_style, - box_width=config.box_width, finger_radius=fr, - finger_axis=config.finger_recess_axis, outer_margin=outer_margin, - ) - layout_bounds = np.array([m.bounds for m in layout]) - bmin = layout_bounds[:, 0, :].min(axis=0) - bmax = layout_bounds[:, 1, :].max(axis=0) - arranged, translations = [], [] - for i, d in enumerate(dilated): - trans = layout[i].bounds.mean(axis=0) - rotated[i].bounds.mean(axis=0) - trans[2] = 0.0 # Z-Achse stabil lassen - d_copy = d.copy() - d_copy.apply_translation(trans) - arranged.append(d_copy) - translations.append(trans[:2]) - - pad = config.clearance + config.voxel_pitch - bmin = bmin - pad - bmax = bmax + pad - - # Die Referenz ist bei der Web-App unrotiert, die real angeordneten Figuren - # sind es nicht. Ohne diese Vereinigung dimensioniert eine Rotation die Box - # nach der ungedrehten Figur und die gedrehte ragt seitlich heraus. - real_bounds = np.array([m.bounds for m in arranged]) - real_min = real_bounds[:, 0, :].min(axis=0) - real_max = real_bounds[:, 1, :].max(axis=0) - bmin[:2] = np.minimum(bmin[:2], real_min[:2]) - bmax[:2] = np.maximum(bmax[:2], real_max[:2]) - - # Z kommt immer aus den realen Figuren – der Slot-Versatz ist XY-only, ein - # Referenz-Z waere bei Rotation schlicht die falsche Hoehe. Zuschlag ist - # voxel_pitch/2 je Seite: genau die Inflation, die _solidify_figure beim - # Marching Cubes auftraegt (gemessen Wuerfel/Kugel/Zylinder identisch, - # 2026-08). Ohne sie faellt die Bodenwand um pitch/2 zu duenn aus, mit dem - # frueheren clearance + voxel_pitch war sie bis zu 2.5 mm zu dick. - z_pad = config.voxel_pitch / 2 - bmin[2] = real_min[2] - z_pad - bmax[2] = real_max[2] + z_pad - if config.enable_finger_recesses: - axis = 0 if config.finger_recess_axis == "x" else 1 - bmin[axis] -= config.finger_radius - bmax[axis] += config.finger_radius - return arranged, (bmin, bmax), translations +def _to_manifold(mesh: trimesh.Trimesh) -> Manifold: + """Same conversion trimesh.boolean uses for engine='manifold'.""" + return Manifold(Mesh( + vert_properties=np.asarray(mesh.vertices, dtype=np.float32), + tri_verts=np.asarray(mesh.faces, dtype=np.uint32), + )) -def _is_manifold(m: trimesh.Trimesh) -> bool: - """Prüft, ob ein Mesh manifold (wasserdicht) ist.""" - return m.is_watertight and len(m.faces) > 0 +def _to_trimesh(manifold: Manifold) -> trimesh.Trimesh: + mesh = manifold.to_mesh() + return trimesh.Trimesh( + vertices=mesh.vert_properties[:, :3], faces=mesh.tri_verts, process=False + ) def _solidify_figure( - fig: trimesh.Trimesh, config: Config, + fig: trimesh.Trimesh, config: Config, top_z: float, ) -> trimesh.Trimesh: - """Solidifiziert eine Figur von ihrer Unterkante nach oben (hinterschnittfrei). + """Solidifies a figure from its underside up to `top_z` (no undercuts). - Füllt alle Voxel von der lokalen Unterkante (z_min) jeder Spalte bis zum - oberen Rand des Gitters. Dies bildet die Form der Unterseite der Figur exakt ab, - zieht aber alle Wände nach oben hin gerade durch, um Hinterschnitte zu vermeiden. + Every voxel column is filled from its lowest occupied voxel up to `top_z`: + the underside keeps the figure's shape, the walls go straight up. Filling + only up to the top of the figure's own grid sealed the cavity whenever the + figure ended below the box's top face (depth_fraction 1.0 with a negative + Z offset, a short figure lowered by hand): the print had a closed void. """ - sol_vox = cast(Any, fig.voxelized(pitch=config.voxel_pitch)) - matrix = sol_vox.matrix.copy() + pitch = config.voxel_pitch + sol_vox = cast(Any, fig.voxelized(pitch=pitch)) + matrix = sol_vox.matrix + # Extend the grid upwards only - the origin sits at the bottom, so the + # transform stays valid (no _padded_transform: the padding is one-sided). + grid_top = sol_vox.transform[2, 3] + (matrix.shape[2] - 1) * pitch + n_extra = max(0, math.ceil((top_z - grid_top) / pitch)) + matrix = np.pad(matrix, ((0, 0), (0, 0), (0, n_extra)), constant_values=False) nz = matrix.shape[2] z_coords = np.arange(nz).reshape(1, 1, nz) has_voxel = matrix.any(axis=2) # (nx, ny) - # argmax liefert den ersten belegten Z-Index je Spalte ohne (nx,ny,nz)-grosses - # Zwischenarray; leere Spalten ergeben 0, werden aber durch has_voxel maskiert + # argmax yields the first occupied Z index per column without an + # (nx, ny, nz) temporary; empty columns give 0 but are masked by has_voxel z_min = matrix.argmax(axis=2)[:, :, np.newaxis] - fill_mask = has_voxel[:, :, np.newaxis] & (z_coords >= z_min) - matrix |= fill_mask + matrix |= has_voxel[:, :, np.newaxis] & (z_coords >= z_min) return _grid_to_mesh(matrix, sol_vox.transform) +def _finger_band(pitch: float) -> float: + """Width of the vertex band around the grip position (see FINGER_BAND_VOXELS).""" + return max(FINGER_BAND_MIN_MM, FINGER_BAND_VOXELS * pitch) + + +def _recess_template(config: Config) -> trimesh.Trimesh: + """Finger recess: a lower hemisphere with a vertical shaft on top. + + The shaft reaches CUT_OVERSHOOT_MM above the box's top face once the + recess sits finger_recess_z_offset below it. A bare hemisphere left solid + material over a lowered recess: reachable only through the figure's own + cavity and printed as an unsupported overhang. + """ + r = config.finger_radius + shaft = config.finger_recess_z_offset + CUT_OVERSHOOT_MM + angles = np.linspace(-np.pi / 2, 0.0, RECESS_ARC_SEGMENTS + 1) + profile = np.column_stack([r * np.cos(angles), r * np.sin(angles)]) + profile[0, 0] = 0.0 # exactly on the axis, so the revolved bottom is closed + profile = np.vstack([profile, [[r, shaft], [0.0, shaft]]]) + return trimesh.creation.revolve(profile, sections=RECESS_SECTIONS) + + +def _recess_pair( + fig: trimesh.Trimesh, template: trimesh.Trimesh, config: Config, position: float +) -> list[trimesh.Trimesh]: + """The two recesses of one figure, beside it at the grip position. + + Expects the figure in build_inlay's frame (box top at z = 0). The recesses + sit on the figure's real silhouette at the grip position, along + finger_recess_axis ("x": thumb and fingers from the sides, "y": front and + back). `position` slides the pair along the figure, relative to its usable + half length (half extent minus finger_radius), so one value fits figures of + any size; a figure shorter than 2 * finger_radius keeps them centred. + """ + axis = 0 if config.finger_recess_axis == "x" else 1 + cross = 1 - axis + fb = fig.bounds + half_span = max(0.0, (fb[1][cross] - fb[0][cross]) / 2.0 - config.finger_radius) + grip = float(fb.mean(axis=0)[cross] + position * half_span) + + verts = fig.vertices + near = verts[np.abs(verts[:, cross] - grip) < _finger_band(config.voxel_pitch)] + # An empty band is possible where the figure has a gap at the grip position + edges = (near[:, axis].min(), near[:, axis].max()) if len(near) else (fb[0][axis], fb[1][axis]) + + pair = [] + for edge in edges: + where = np.zeros(3) + where[axis], where[cross], where[2] = edge, grip, -config.finger_recess_z_offset + recess = template.copy() + recess.apply_translation(where) + pair.append(recess) + return pair + + +def _wall_check( + box: Manifold, cutters: list[Manifold], inlay: Manifold, config: Config, + apothem: float | None = None, +) -> dict: + """Measures every wall of the finished inlay exactly, per figure. + + Each figure's cutter (cavity plus its recesses) is clipped to the box; + for axis-parallel walls the thinnest point of a pocket is exactly its + bounds' distance to the box face, for the cylinder the farthest vertex + (a convex function peaks at a vertex). Walls between two pockets come + from manifold3d's min_gap. Findings name the figure (index) they belong + to - the old voxel check overestimated walls by up to a pitch, ignored + the walls between cavities and passed an inlay without any cavity. + """ + wall, gap = config.wall_thickness, config.effective_figure_gap + tol = WALL_TOLERANCE_MM + bx = np.array(box.bounding_box()) # x0, y0, z0, x1, y1, z1 + centre = (bx[:2] + bx[3:5]) / 2 + violations: list[dict] = [] + outer: list[float] = [] + + def flag(kind: str, figure: int | None, measured: float, target: float, + other: int | None = None) -> None: + violations.append({"figure": figure, "kind": kind, "measured_mm": round(float(measured), 3), + "target_mm": float(target), "other": other}) + + clips = [cutter ^ box for cutter in cutters] + bounds: list[np.ndarray | None] = [] + for i, clip in enumerate(clips): + if clip.is_empty() or clip.volume() < _MIN_VOLUME_MM3: + flag("no_cavity", i, 0.0, wall) + bounds.append(None) + continue + bb = np.array(clip.bounding_box()) + bounds.append(bb) + if apothem is not None: + xy = clip.to_mesh().vert_properties[:, :2] + side = apothem - float(np.linalg.norm(xy - centre, axis=1).max()) + else: + side = float(min(bb[0] - bx[0], bx[3] - bb[3], bb[1] - bx[1], bx[4] - bb[4])) + floor = float(bb[2] - bx[2]) + outer += [side, floor] + if side < wall - tol: + flag("side", i, side, wall) + if floor < wall - tol: + flag("floor", i, floor, wall) + + for i, a in enumerate(bounds): + for j in range(i + 1, len(bounds)): + b = bounds[j] + if a is None or b is None or np.maximum(b[:3] - a[3:], a[:3] - b[3:]).max() >= gap: + continue + if (clips[i] ^ clips[j]).volume() > _MIN_VOLUME_MM3: + flag("merged", i, 0.0, gap, j) + else: + measured = clips[i].min_gap(clips[j], gap) + if measured < gap - tol: + flag("inner", i, measured, gap, j) + + # An enclosed void is a separate shell with negative volume + for part in inlay.decompose(): + if part.volume() < 0: + vb = np.array(part.bounding_box()) + owner = next( + (i for i, bb in enumerate(bounds) + if bb is not None and np.all(vb[:3] <= bb[3:]) and np.all(bb[:3] <= vb[3:])), + None, + ) + flag("sealed", owner, 0.0, wall) + + return { + "min_wall_mm": min(outer) if outer else float(wall), + "passes_min_wall": not violations, + "target_mm": float(wall), + "violations": violations, + } + + def build_inlay( - figure_offsets: "trimesh.Trimesh | list[trimesh.Trimesh]", + figures: "trimesh.Trimesh | list[trimesh.Trimesh]", config: Config = _DEFAULT_CFG, individual_offsets: list[tuple[float, float, float]] | None = None, - stable_global_bounds: tuple[np.ndarray, np.ndarray] | None = None, file_names: list[str] | None = None, individual_recess_positions: list[float] | None = None, + sorting_reference: list[trimesh.Trimesh] | None = None, ) -> tuple[trimesh.Trimesh, float, float, float]: - """Konstruiert die Box und fuehrt die Boolean-Differenz aus. - - Akzeptiert ein einzelnes Mesh (Abwaertskompatibilitaet) oder eine Liste - von Meshes fuer Multi-Figur-Inlays. - - Die Box-Form steuert config.box_shape: "box" (Quader) oder "cylinder" - (Zylinder). Beim Zylinder sind die zurueckgegebenen box_w und box_d beide - gleich dem Durchmesser (Bounding-Box des Zylinders). - - `individual_recess_positions` sets the finger recess position per figure - (same value range as `Config.finger_recess_position`); figures without an - entry fall back to the config value. Every other recess parameter (radius, - axis, Z offset) stays global - the grip point differs per figure, the hand - that reaches in does not. - - Hinweis: Rotationen sind zu diesem Zeitpunkt bereits in die uebergebenen - Meshes eingerechnet (`apply_euler_rotation` laeuft in Schritt 1 der - Pipeline). `build_inlay` dreht selbst nichts mehr. + """Arranges the dilated figures, cuts them from a box and checks the walls. + + Takes one mesh or a list (the output of `dilate`, rotations already + applied - build_inlay never rotates). Per figure: + + - **Z:** it sinks `depth_fraction` of its *own* height below the box's + top face, so every figure stands out by the same share of its height, + wherever its STL sits in Z and however tall the others are. + - **Cutter:** its voxel solid, filled from the underside up past the top + face (no undercuts, never a sealed void), plus the two finger recesses. + + The box is then dimensioned from those real cutters rather than from + predicted ones: voxelization shifts a cavity by up to half a pitch + depending on where it lies on the grid, so only measuring makes the walls + exact. The layout (`arrange_footprints`) spaces the cutters' footprints + exactly `figure_gap` apart, the box adds `wall_thickness` around them and + below the deepest one. Manual box dimensions replace the automatic ones; + walls they make too thin are reported, not silently accepted. + + `individual_offsets` move a figure *inside* that box - the box does not + follow them. `individual_recess_positions` sets the grip position per + figure (falling back to `Config.finger_recess_position`); radius, axis and + Z offset stay global because they describe the hand, not the figure. + `sorting_reference` (e.g. the unrotated figures) fixes the layout order so + it does not jump while a figure is being rotated. + + Metadata on the returned inlay: `wall_check` (see `_wall_check`), + `violating_indices`, `placements` (per figure, the translation applied to + the mesh that was passed in) and `finger_recesses` (for the preview). + Returns (inlay, box_w, box_d, box_h); for a cylinder box_w == box_d is the + diameter. """ - # Normalisieren: einzelnes Mesh → einelementige Liste - if isinstance(figure_offsets, trimesh.Trimesh): - figure_offsets = [figure_offsets] - + if isinstance(figures, trimesh.Trimesh): + figures = [figures] # Validate up front: a value outside [-1, 1] would push a recess past the - # figure's footprint into a box wall, and failing after the CSG run would - # waste the whole build. - if individual_recess_positions is not None: - for value in individual_recess_positions: - if not -1.0 <= value <= 1.0: - raise ValueError(t_("config.bad_finger_position", value=value)) - - for f in figure_offsets: + # figure's footprint, and failing after the CSG run would waste the build. + for value in individual_recess_positions or []: + if not -1.0 <= value <= 1.0: + raise ValueError(t_("config.bad_finger_position", value=value)) + for f in figures: if f.bounds is None or len(f.vertices) == 0: raise ValueError(t_("error.empty_meshes")) - multi = len(figure_offsets) > 1 - n_figs = len(figure_offsets) - - # Kombinierte Bounding-Box aller Figuren - if stable_global_bounds is not None: - bmin, bmax = stable_global_bounds - # Box-Hoehe: depth_fraction bezieht sich auf die hoechste Figur. - # arrange_with_stable_bounds hat die Solidify-Inflation bereits - # eingerechnet, hier kommt nichts mehr dazu. - max_z_extent = float(bmax[2] - bmin[2]) - else: - all_bounds = np.array([f.bounds for f in figure_offsets]) # (n, 2, 3) - bmin = all_bounds[:, 0, :].min(axis=0) - bmax = all_bounds[:, 1, :].max(axis=0) - # Ohne stabile Bounds fehlt der Ausgleich fuer die Inflation, die - # _solidify_figure auftraegt: die Kavitaet reicht pro Seite um - # voxel_pitch/2 weiter als das uebergebene Mesh, sonst faellt die - # Bodenwand entsprechend zu duenn aus. - raw_z_extent = float(all_bounds[:, 1, 2].max() - all_bounds[:, 0, 2].min()) - max_z_extent = raw_z_extent + config.voxel_pitch - fig_size = bmax - bmin - cylinder = config.box_shape == "cylinder" - - # Box-Masse - auto_h = config.wall_thickness + config.depth_fraction * max_z_extent - box_h = config.box_height if config.box_height is not None else auto_h - label_multi = t_("pipeline.multi_suffix", n=n_figs) if multi else "" + n = len(figures) + multi = n > 1 + wall = config.wall_thickness - if cylinder: - # Umkreis des Figuren-Rechtecks: garantiert die Wandstaerke auch an - # den Ecken der (unbekannt gefuellten) Bounding-Box - auto_diameter = float(np.hypot(fig_size[0], fig_size[1])) + 2 * config.wall_thickness - diameter = config.box_diameter if config.box_diameter is not None else auto_diameter - box_w = box_d = float(diameter) + def entry(values, i, default): + return values[i] if values is not None and i < len(values) else default - if diameter < auto_diameter or box_h < auto_h: - _log( - t_("pipeline.warn_cylinder_small", d=f"{diameter:.1f}", h=f"{box_h:.1f}", - min_d=f"{auto_diameter:.1f}", min_h=f"{auto_h:.1f}") - ) - - # Segmentlaenge ~1 mm haelt den Sehnenfehler weit unter clearance/voxel_pitch - sections = int(np.clip(np.pi * diameter, 64, 512)) - box = trimesh.creation.cylinder( - radius=diameter / 2.0, height=box_h, sections=sections - ) - _log( - t_("pipeline.box_cylinder", d=f"{diameter:.1f}", h=f"{box_h:.1f}", - suffix=label_multi, - mode=t_("pipeline.manual") - if any(v is not None for v in [config.box_diameter, config.box_height]) - else t_("pipeline.automatic")) - ) - else: - auto_xy = fig_size[:2] + 2 * config.wall_thickness - box_w = config.box_width if config.box_width is not None else auto_xy[0] - box_d = config.box_depth if config.box_depth is not None else auto_xy[1] - - # Warnen, falls manuelle Masse zu klein - if box_w < auto_xy[0] or box_d < auto_xy[1] or box_h < auto_h: - _log( - t_("pipeline.warn_box_small", w=f"{box_w:.1f}", d=f"{box_d:.1f}", h=f"{box_h:.1f}", - min_w=f"{auto_xy[0]:.1f}", min_d=f"{auto_xy[1]:.1f}", min_h=f"{auto_h:.1f}") - ) - - box = trimesh.creation.box(extents=[box_w, box_d, box_h]) - _log( - t_("pipeline.box", w=f"{box_w:.1f}", d=f"{box_d:.1f}", h=f"{box_h:.1f}", - suffix=label_multi, - mode=t_("pipeline.manual") - if any(v is not None for v in [config.box_width, config.box_depth, config.box_height]) - else t_("pipeline.automatic")) - ) - - # Positionierung: Boden bei z=0, Box zentriert ueber allen Figuren - center_x = (bmin[0] + bmax[0]) / 2 - center_y = (bmin[1] + bmax[1]) / 2 - box.apply_translation([center_x, center_y, box_h / 2]) - - # Absolute Box-Wandgrenzen zur Wandstärken-Verifikation - left_wall = center_x - box_w / 2 - right_wall = center_x + box_w / 2 - front_wall = center_y - box_d / 2 - back_wall = center_y + box_d / 2 - - # Jede Figur in Z verschieben (Unterkante auf Bodenwand) und solidifizieren - placed_figs: list[trimesh.Trimesh] = [] - fig_labels: list[str] = [] - finger_cylinders: list[trimesh.Trimesh] = [] - violating_indices = [] - - # Fingermulden-Template (untere Halbkugel) einmalig erzeugen – - # pro Position wird unten nur noch eine Kopie verschoben - recess_template: trimesh.Trimesh | None = None - if config.enable_finger_recesses: - r = config.finger_radius - sphere = trimesh.creation.icosphere(subdivisions=3, radius=r) - top_box = trimesh.creation.box(extents=[3.0 * r, 3.0 * r, 2.0 * r]) - top_box.apply_translation([0.0, 0.0, r]) - recess_template = cast( - trimesh.Trimesh, - trimesh.boolean.difference([sphere, top_box], engine="manifold"), - ) + offsets = [ + np.asarray(entry(individual_offsets, i, (config.offset_x, config.offset_y, config.offset_z)), + dtype=float) + for i in range(n) + ] + labels = [ + f" '{file_names[i]}'" if file_names is not None and i < len(file_names) + else (f" ({i + 1}/{n})" if multi else "") + for i in range(n) + ] - for i, fig in enumerate(figure_offsets): - fig = fig.copy() + # Frame: the box's top face at z = 0, each figure sunk by depth_fraction + # of its own height. + sink, local = [], [] + for fig in figures: fb = fig.bounds - if individual_offsets is not None and i < len(individual_offsets): - ox, oy, oz = individual_offsets[i] - else: - ox, oy, oz = config.offset_x, config.offset_y, config.offset_z - - fig_h = fb[1][2] - fb[0][2] - z_pos = box_h + (1 - config.depth_fraction) * max_z_extent - fig_h + oz - fig.apply_translation( - [ - ox, - oy, - z_pos - fb[0][2], - ] - ) - - # Wandstärken-Vorab-Check für diese Figur zu den Box-Wänden - fb_placed = fig.bounds - d_bottom = fb_placed[0][2] # Z-Abstand zum Boden (z=0) - if cylinder: - # Radialer Abstand des figurenfernsten Vertex zur Zylinderwand - r_fig = float( - np.linalg.norm(fig.vertices[:, :2] - [center_x, center_y], axis=1).max() - ) - min_w_i = min(box_w / 2 - r_fig, d_bottom) - else: - d_left = fb_placed[0][0] - left_wall - d_right = right_wall - fb_placed[1][0] - d_front = fb_placed[0][1] - front_wall - d_back = back_wall - fb_placed[1][1] - min_w_i = min(d_left, d_right, d_front, d_back, d_bottom) - # Wenn Wandstärke unterschritten wird (mit 0.1 mm Voxel-Toleranz) - if min_w_i < (config.wall_thickness - 0.1): - violating_indices.append(i) - - # Generate the finger recess bodies - if config.enable_finger_recesses and recess_template is not None: - # Determine the real silhouette edges of the already placed (and - # possibly rotated) model at the grip position. - # config.finger_recess_axis picks the axis the recesses lie on: - # "x" -> left/right (thumb and fingers grip from the sides), - # "y" -> front/back (natural hand position). - axis = 0 if config.finger_recess_axis == "x" else 1 - cross = 1 - axis - global_min, global_max = None, None - c_placed = fb_placed.mean(axis=0) - verts = fig.vertices - - # Where along the figure the pair of recesses sits (cross axis). - # finger_recess_position is relative to the usable half length, so - # the same setting works for figures of different sizes. Subtracting - # the recess radius keeps the hemisphere inside the figure's own - # footprint, hence away from the box walls, even at +/-1.0. For a - # figure shorter than 2 * finger_radius the span collapses to 0 and - # the recesses stay centred. - half_span = max( - 0.0, - (fb_placed[1][cross] - fb_placed[0][cross]) / 2.0 - config.finger_radius, - ) - if individual_recess_positions is not None and i < len(individual_recess_positions): - recess_position = individual_recess_positions[i] - else: - recess_position = config.finger_recess_position - grip_cross = float(c_placed[cross] + recess_position * half_span) - - # Collect the vertices near that grip position along the cross axis. - # The band width scales with voxel_pitch (see FINGER_BAND_VOXELS) so - # a coarse resolution still yields enough vertices. - band = max(FINGER_BAND_MIN_MM, FINGER_BAND_VOXELS * config.voxel_pitch) - close_verts = verts[np.abs(verts[:, cross] - grip_cross) < band] - if len(close_verts) > 0: - global_min = float(close_verts[:, axis].min()) - global_max = float(close_verts[:, axis].max()) - - # Fallback to the global bounds of the placed figure (an empty band - # is possible when the figure has a gap at the chosen position) - if global_min is None or global_max is None: - global_min = float(fb_placed[0][axis]) - global_max = float(fb_placed[1][axis]) - - # Copy the hemisphere template (open at the top, radius = finger_radius) - cyl_a = recess_template.copy() - cyl_b = recess_template.copy() - - # Placed at the box's top edge, lowered by the Z offset - z_pos = box_h - config.finger_recess_z_offset - pos_a = [0.0, 0.0, z_pos] - pos_b = [0.0, 0.0, z_pos] - pos_a[axis] = global_min - pos_b[axis] = global_max - pos_a[cross] = grip_cross - pos_b[cross] = grip_cross - - cyl_a.apply_translation(pos_a) - cyl_b.apply_translation(pos_b) - - # Tag them so the preview can identify the recesses - cyl_a.metadata["type"] = "finger_recess" - cyl_a.metadata["fig_idx"] = i - cyl_b.metadata["type"] = "finger_recess" - cyl_b.metadata["fig_idx"] = i - - finger_cylinders.extend([cyl_a, cyl_b]) - - label = f" '{file_names[i]}'" if (file_names is not None and i < len(file_names)) else (f" ({i + 1}/{n_figs})" if multi else "") - placed_figs.append(fig) - fig_labels.append(label) - - # Solidifizierung ist pro Figur unabhaengig → optional parallel - def _solidify_logged(idx: int) -> trimesh.Trimesh: - t = _log(t_("pipeline.solidify", label=fig_labels[idx])) - solid = _solidify_figure(placed_figs[idx], config) + dz = -config.depth_fraction * (fb[1][2] - fb[0][2]) - fb[0][2] + moved = fig.copy() + moved.apply_translation([0.0, 0.0, dz]) + sink.append(dz) + local.append(moved) + + def solidify_logged(i: int) -> trimesh.Trimesh: + t = _log(t_("pipeline.solidify", label=labels[i])) + # The Z offset is applied afterwards; fill far enough that the cavity + # still reaches past the top face once it has moved. + solid = _solidify_figure(local[i], config, top_z=CUT_OVERSHOOT_MM - offsets[i][2]) _log(t_("pipeline.solidified", faces=f"{len(solid.faces):,}"), t) return solid - solidified = _parallel_map( - _solidify_logged, range(n_figs), config, what=t_("pipeline.what.solidify") + solids = _parallel_map( + solidify_logged, range(n), config, what=t_("pipeline.what.solidify") ) - - for label, solid in zip(fig_labels, solidified): + for label, solid in zip(labels, solids): if not _is_manifold(solid): - raise ValueError( - t_("error.not_manifold", label=label) - ) + raise ValueError(t_("error.not_manifold", label=label)) - # Vorab-Pruefung Box - if not _is_manifold(box): - raise ValueError( - "Box ist nicht manifold / watertight. " - "CSG wuerde wahrscheinlich fehlschlagen." - ) - - # CSG-Boolean: Box minus alle Figuren und Fingermulden - csg_label = ( - t_("pipeline.csg_label_multi", n=n_figs) if multi - else t_("pipeline.csg_label_single") + recesses: list[list[trimesh.Trimesh]] = [[] for _ in range(n)] + if config.enable_finger_recesses: + # Built once, copied per figure (AGENTS.md: reuse geometry templates) + template = _recess_template(config) + for i in range(n): + position = entry(individual_recess_positions, i, config.finger_recess_position) + recesses[i] = _recess_pair(local[i], template, config, position) + + # Everything cut per figure, before the manual offsets: layout and box + # are measured on these. + lo = np.array([np.min([m.bounds[0] for m in [solids[i]] + recesses[i]], axis=0) for i in range(n)]) + hi = np.array([np.max([m.bounds[1] for m in [solids[i]] + recesses[i]], axis=0) for i in range(n)]) + sort_keys = ( + None if sorting_reference is None + else [float(np.prod(m.extents[:2])) for m in sorting_reference] ) + corners = arrange_footprints( + hi[:, :2] - lo[:, :2], config.effective_figure_gap, config.layout_style, + sort_keys, config.box_width, margin=wall, + ) + slots = np.zeros((n, 3)) + slots[:, :2] = corners - lo[:, :2] + fp_lo = (lo[:, :2] + slots[:, :2]).min(axis=0) + fp_hi = (hi[:, :2] + slots[:, :2]).max(axis=0) + span = fp_hi - fp_lo + centre = (fp_lo + fp_hi) / 2 + + auto_h = wall - float(lo[:, 2].min()) + box_h = config.box_height if config.box_height is not None else auto_h + label_multi = t_("pipeline.multi_suffix", n=n) if multi else "" + apothem = None + if config.box_shape == "cylinder": + # Circumcircle of the footprints' rectangle: the wall holds at its + # corners too, however they are filled + auto_diameter = float(np.hypot(*span)) + 2 * wall + diameter = config.box_diameter if config.box_diameter is not None else auto_diameter + box_w = box_d = float(diameter) + if diameter < auto_diameter or box_h < auto_h: + _log(t_("pipeline.warn_cylinder_small", d=f"{diameter:.1f}", h=f"{box_h:.1f}", + min_d=f"{auto_diameter:.1f}", min_h=f"{auto_h:.1f}")) + # Segment length ~1 mm keeps the chord error far below any tolerance + sections = int(np.clip(np.pi * diameter, 64, 512)) + box = trimesh.creation.cylinder(radius=diameter / 2.0, height=box_h, sections=sections) + # The prism's flat sides are the closest the wall gets to the axis + apothem = diameter / 2.0 * math.cos(math.pi / sections) + manual = config.box_diameter is not None or config.box_height is not None + _log(t_("pipeline.box_cylinder", d=f"{diameter:.1f}", h=f"{box_h:.1f}", suffix=label_multi, + mode=t_("pipeline.manual") if manual else t_("pipeline.automatic"))) + else: + auto_w, auto_d = (span + 2 * wall).tolist() + box_w = config.box_width if config.box_width is not None else auto_w + box_d = config.box_depth if config.box_depth is not None else auto_d + if box_w < auto_w or box_d < auto_d or box_h < auto_h: + _log(t_("pipeline.warn_box_small", w=f"{box_w:.1f}", d=f"{box_d:.1f}", h=f"{box_h:.1f}", + min_w=f"{auto_w:.1f}", min_d=f"{auto_d:.1f}", min_h=f"{auto_h:.1f}")) + box = trimesh.creation.box(extents=[box_w, box_d, box_h]) + manual = any(v is not None for v in (config.box_width, config.box_depth, config.box_height)) + _log(t_("pipeline.box", w=f"{box_w:.1f}", d=f"{box_d:.1f}", h=f"{box_h:.1f}", suffix=label_multi, + mode=t_("pipeline.manual") if manual else t_("pipeline.automatic"))) + box.apply_translation([centre[0], centre[1], -box_h / 2.0]) + + moves = [slots[i] + offsets[i] for i in range(n)] + for i in range(n): + solids[i].apply_translation(moves[i]) + for recess in recesses[i]: + # Recesses follow the figure in XY; their depth is set from the top face + recess.apply_translation([moves[i][0], moves[i][1], 0.0]) + + csg_label = t_("pipeline.csg_label_multi", n=n) if multi else t_("pipeline.csg_label_single") if config.enable_finger_recesses: csg_label += t_("pipeline.csg_label_recesses") t = _log(t_("pipeline.csg", label=csg_label)) try: - inlay = trimesh.boolean.difference( - [box] + solidified + finger_cylinders, engine="manifold" - ) + box_m = _to_manifold(box) + cutters = [ + Manifold.batch_boolean([_to_manifold(m) for m in [solids[i]] + recesses[i]], OpType.Add) + for i in range(n) + ] + inlay_m = box_m - Manifold.batch_boolean(cutters, OpType.Add) + inlay = _to_trimesh(inlay_m) except Exception as exc: - raise RuntimeError( - t_("error.csg_failed") - ) from exc - - if inlay is None or len(inlay.faces) == 0: - raise ValueError( - t_("error.csg_empty") - ) - + raise RuntimeError(t_("error.csg_failed")) from exc + if len(inlay.faces) == 0: + raise ValueError(t_("error.csg_empty")) _log(t_("pipeline.csg_result", faces=f"{len(inlay.faces):,}"), t) - # Verschiebe das Inlay so, dass die linke vordere Ecke der Box bei (0, 0, 0) liegt. - shift_x = (bmin[0] + bmax[0]) / 2 - box_w / 2 - shift_y = (bmin[1] + bmax[1]) / 2 - box_d / 2 - inlay.apply_translation([-shift_x, -shift_y, 0.0]) - - # Speichere verletzende Indizes und Fingermulden-Meshes in den Metadaten des Inlays - inlay.metadata["violating_indices"] = violating_indices - # Die Z-Ausdehnung, mit der die Figuren platziert wurden. Die 3D-Vorschau - # der Web-App muss damit rechnen statt sie nachzubilden, sonst zeichnet sie - # die Figuren auf einer anderen Hoehe als die tatsaechliche Kavitaet. - inlay.metadata["max_z_extent"] = max_z_extent - if config.enable_finger_recesses: - # Kopie der Zylinder verschieben, um mit dem Inlay ausgerichtet zu sein - shifted_recesses = [] - for cyl in finger_cylinders: - cyl_copy = cyl.copy() - cyl_copy.apply_translation([-shift_x, -shift_y, 0.0]) - shifted_recesses.append(cyl_copy) - inlay.metadata["finger_recesses"] = shifted_recesses - - # Voxelgitter des Hohlraums fuer die Wandstaerkenpruefung aufbauen - pitch = config.voxel_pitch - nx = max(1, int(round(box_w / pitch))) - ny = max(1, int(round(box_d / pitch))) - nz = max(1, int(round(box_h / pitch))) - cavity_grid = np.zeros((nx, ny, nz), dtype=bool) - - shifted_cutouts = [m.copy() for m in (solidified + finger_cylinders)] - for m in shifted_cutouts: - m.apply_translation([-shift_x, -shift_y, 0.0]) - vox = cast(Any, m.voxelized(pitch=pitch)) - vox.fill() - origin = vox.transform[:3, 3] - gx0 = int(round(origin[0] / pitch)) - gy0 = int(round(origin[1] / pitch)) - gz0 = int(round(origin[2] / pitch)) - shape = vox.matrix.shape - - gx1 = min(nx, gx0 + shape[0]) - gy1 = min(ny, gy0 + shape[1]) - gz1 = min(nz, gz0 + shape[2]) - - gx0_c = max(0, gx0) - gy0_c = max(0, gy0) - gz0_c = max(0, gz0) - - sx0 = gx0_c - gx0 - sy0 = gy0_c - gy0 - sz0 = gz0_c - gz0 - - sx1 = gx1 - gx0 - sy1 = gy1 - gy0 - sz1 = gz1 - gz0 - - # Nur Zellen uebernehmen, die vollstaendig in den Bounds DIESER Figur liegen. - # Randzellen sind durch die Voxelisierung aufgeblaeht und wuerden sonst eine - # zu duenne Wand vortaeuschen. Die Begrenzung darf nur den Bereich dieser - # Figur betreffen – ein globales Loeschen wuerde bereits eingetragene - # Figuren wieder ausradieren (Multi-Figur-Inlays). - mb = m.bounds - lo = [ - max(0, gx0_c, int(np.ceil(mb[0][0] / pitch))), - max(0, gy0_c, int(np.ceil(mb[0][1] / pitch))), - max(0, gz0_c, int(np.ceil(mb[0][2] / pitch))), - ] - hi = [ - min(gx1, int(np.floor(mb[1][0] / pitch))), - min(gy1, int(np.floor(mb[1][1] / pitch))), - min(gz1, int(np.floor(mb[1][2] / pitch))), - ] - - if all(lo[i] < hi[i] for i in range(3)): - src = tuple(slice(lo[i] - (gx0, gy0, gz0)[i], hi[i] - (gx0, gy0, gz0)[i]) for i in range(3)) - dst = tuple(slice(lo[i], hi[i]) for i in range(3)) - cavity_grid[dst] |= vox.matrix[src] - - inlay.metadata["cavity_grid"] = cavity_grid + wall_check = _wall_check(box_m, cutters, inlay_m, config, apothem) - return inlay, box_w, box_d, box_h + # Box corner to the origin + shift = np.array([centre[0] - box_w / 2.0, centre[1] - box_d / 2.0, -box_h]) + inlay.apply_translation(-shift) + inlay.metadata["wall_check"] = wall_check + inlay.metadata["violating_indices"] = sorted( + {v["figure"] for v in wall_check["violations"] if v["figure"] is not None} + ) + inlay.metadata["placements"] = [ + np.array([0.0, 0.0, sink[i]]) + moves[i] - shift for i in range(n) + ] + if config.enable_finger_recesses: + shown = [] + for i in range(n): + for recess in recesses[i]: + recess.apply_translation(-shift) + recess.metadata["type"] = "finger_recess" + recess.metadata["fig_idx"] = i + shown.append(recess) + inlay.metadata["finger_recesses"] = shown + + return inlay, float(box_w), float(box_d), float(box_h) + + +def wall_thickness_stats_3d(inlay: trimesh.Trimesh) -> dict: + """Returns (and logs) the wall check `build_inlay` ran on this inlay. + + Keys: `min_wall_mm` (thinnest side or floor wall), `passes_min_wall` + (no finding at all), `target_mm` and `violations` - one entry per finding + with the figure index, its kind ("side", "floor", "inner", "merged", + "sealed", "no_cavity"), the measured and the target value in mm and, for + walls between two cavities, the other figure. The target of "inner" and + "merged" is the figure gap, of every other kind the wall thickness. + """ + t = _log(t_("pipeline.wall_verify")) + check = getattr(inlay, "metadata", {}).get("wall_check") + if check is None: + raise ValueError(t_("error.no_wall_check")) + _log(t_("pipeline.min_wall", measured=f"{check['min_wall_mm']:.2f}", target=check["target_mm"]), t) + return dict(check) -def wall_thickness_stats_3d( - inlay: trimesh.Trimesh, config: Config = _DEFAULT_CFG -) -> dict: - """Berechnet die minimale Wandstärke der Box-Außenwände (Seitenwände und Boden). +# Exit code of the CLI when the wall check fails. Not 2: argparse exits with 2 +# on a usage error, and a script must be able to tell the two apart. +EXIT_CHECK_FAILED: Final[int] = 3 - Bei box_shape="cylinder" wird der radiale Abstand zur Mantelfläche statt - der Distanz zum X/Y-Gitterrand verwendet. - Bewusst nur das Minimum: Mittel-/Maximalwerte der Voxel-Distanzen wären - Kavitätstiefen, keine Wandstärken, und damit irreführend. - """ - t = _log(t_("pipeline.wall_verify")) - - pitch = config.voxel_pitch - if hasattr(inlay, "metadata") and "cavity_grid" in inlay.metadata: - matrix = inlay.metadata["cavity_grid"] - cavity = matrix.copy() - nx, ny, nz = cavity.shape - elif inlay.bounds is None or len(inlay.vertices) == 0: - cavity = np.zeros((1, 1, 1), dtype=bool) - nx = ny = nz = 1 - else: - vox = cast(Any, inlay.voxelized(pitch=pitch)) - vox.fill() - matrix = vox.matrix - nx, ny, nz = matrix.shape - cavity = ~matrix - - # Distanz jedes Voxels (in Voxel-Einheiten) zur naechsten Aussenwand; - # die Oberseite ist offen. Achsenweise Distanzfelder werden zu einem - # 3D-Feld kombiniert – nur ein Gitter-grosses Array statt einer - # Index-Liste pro Hohlraum-Voxel. - if config.box_shape == "cylinder": - cx, cy = (nx - 1) / 2.0, (ny - 1) / 2.0 - dx = np.arange(nx, dtype=np.float32) - cx - dy = np.arange(ny, dtype=np.float32) - cy - r_grid = (min(nx, ny) - 1) / 2.0 - d_side = r_grid - np.sqrt(dx[:, None] ** 2 + dy[None, :] ** 2) # (nx, ny) - cavity = cavity & ((d_side >= 0.5)[:, :, None]) - az = np.arange(nz, dtype=np.float32) - wall_vox = np.minimum(d_side[:, :, None], az[None, None, :]) - else: - ax = np.minimum(np.arange(nx), nx - 1 - np.arange(nx)).astype(np.int32) - ay = np.minimum(np.arange(ny), ny - 1 - np.arange(ny)).astype(np.int32) - az = np.arange(nz, dtype=np.int32) - wall_vox = np.minimum(ax[:, None, None], ay[None, :, None]) - wall_vox = np.minimum(wall_vox, az[None, None, :]) - - n_cavity = int(cavity.sum()) - if n_cavity > 0: - raw_min = pitch * float(np.min(wall_vox, where=cavity, initial=nx + ny + nz)) - min_wall = round(raw_min / pitch) * pitch if raw_min >= 0 else raw_min - else: - min_wall = float(config.wall_thickness) +def describe_violation(violation: dict, names: list[str]) -> str: + """One readable line per wall-check finding, naming the figure(s).""" + def name(i: int | None) -> str: + return names[i] if i is not None and i < len(names) else f"#{'?' if i is None else i + 1}" - _log( - t_("pipeline.min_wall", measured=f"{min_wall:.2f}", target=config.wall_thickness), - t, + return t_( + f"check.{violation['kind']}", + name=name(violation["figure"]), other=name(violation["other"]), + measured=f"{violation['measured_mm']:.2f}", target=f"{violation['target_mm']:.2f}", ) - return { - "min_wall_mm": min_wall, - "passes_min_wall": min_wall >= (config.wall_thickness - 0.1), # Voxel-Toleranz - "target_mm": config.wall_thickness, - } - # --- CLI -------------------------------------------------------------------- if __name__ == "__main__": @@ -1175,7 +1078,7 @@ def wall_thickness_stats_3d( default=i18n.get_language(), env=i18n.ENV_VAR), ) parser.add_argument( - "-i", "--input", nargs="+", default=["figur.stl"], + "-i", "--input", nargs="+", default=[DEFAULT_INPUT], help=t_("cli.input") ) parser.add_argument( @@ -1286,48 +1189,56 @@ def wall_thickness_stats_3d( ) args = parser.parse_args() - - config = Config( - clearance=args.clearance, - wall_thickness=args.wall_thickness, - depth_fraction=args.depth_fraction, - voxel_pitch=args.voxel_pitch, - decimate_faces=args.decimate_faces, - stl_unit_to_mm=args.scale, - box_shape=args.box_shape, - box_width=args.box_width, - box_depth=args.box_depth, - box_height=args.box_height, - box_diameter=args.box_diameter, - offset_x=args.offset_x, - offset_y=args.offset_y, - offset_z=args.offset_z, - figure_gap=args.figure_gap, - layout_style=args.layout_style, - enable_finger_recesses=args.finger_recesses, - finger_radius=args.finger_radius, - finger_recess_axis=args.finger_recess_axis, - finger_recess_z_offset=args.finger_recess_z_offset, - finger_recess_position=args.finger_recess_position[0], - enable_parallel=args.parallel, - ) - input_paths = args.input - multi = len(input_paths) > 1 - t_total = time.perf_counter() - # One value applies to every figure, otherwise one value per input file - - # anything else is a silent mismatch between flags and files. + # Everything that can be rejected is rejected here, before minutes of + # voxel work: argparse then prints a usage error instead of a traceback. + # One recess position applies to every figure, otherwise one per input + # file - only checked when recesses are on, the flag does nothing else. recess_positions = list(args.finger_recess_position) + for value in recess_positions: + if not -1.0 <= value <= 1.0: + parser.error(t_("config.bad_finger_position", value=value)) if len(recess_positions) == 1: recess_positions = recess_positions * len(input_paths) elif len(recess_positions) != len(input_paths): - parser.error( - t_("cli.error.recess_position_count", - given=len(recess_positions), n=len(input_paths)) + if args.finger_recesses: + parser.error( + t_("cli.error.recess_position_count", + given=len(recess_positions), n=len(input_paths)) + ) + print(t_("cli.recess_position_ignored")) + try: + config = Config( + clearance=args.clearance, + wall_thickness=args.wall_thickness, + depth_fraction=args.depth_fraction, + voxel_pitch=args.voxel_pitch, + decimate_faces=args.decimate_faces, + stl_unit_to_mm=args.scale, + box_shape=args.box_shape, + box_width=args.box_width, + box_depth=args.box_depth, + box_height=args.box_height, + box_diameter=args.box_diameter, + offset_x=args.offset_x, + offset_y=args.offset_y, + offset_z=args.offset_z, + figure_gap=args.figure_gap, + layout_style=args.layout_style, + enable_finger_recesses=args.finger_recesses, + finger_radius=args.finger_radius, + finger_recess_axis=args.finger_recess_axis, + finger_recess_z_offset=args.finger_recess_z_offset, + enable_parallel=args.parallel, ) + except ValueError as exc: + parser.error(str(exc)) + + multi = len(input_paths) > 1 + t_total = time.perf_counter() - # Schritt 1: Alle Figuren vorbereiten (optional parallel) + # Step 1: prepare every figure (optionally in parallel) label = (t_("cli.label.figures", n=len(input_paths)) if multi else t_("cli.label.figure")) print(t_("cli.step1", label=label)) @@ -1340,46 +1251,37 @@ def wall_thickness_stats_3d( apply_euler_rotation(m, args.rot_x, args.rot_y, args.rot_z) for m in prepared ] - # Schritt 2: Toleranz-Offset pro Figur (optional parallel) + # Step 2: tolerance offset per figure (optionally in parallel) print(t_("cli.step2")) dilated_meshes = _parallel_map( lambda fig: dilate(fig, config.clearance, config), rotated, config, what=t_("pipeline.what.dilate"), ) - # Schritt 2b: Stabile Anordnung + Box-Bounds (geteilte Logik mit der Web-App). - # Referenz sind die rotierten Figuren: die Rotation steht per CLI-Flag fest, - # die Box soll die gedrehte Figur umschliessen. - if multi: - gap = config.figure_gap if config.figure_gap is not None else config.wall_thickness - print(t_("cli.step2b", n=len(dilated_meshes), gap=f"{gap:.1f}", style=config.layout_style)) - dilated_meshes, stable_bounds, _ = arrange_with_stable_bounds( - rotated, rotated, dilated_meshes, config - ) - - # Schritt 3: Inlay konstruieren (Multi-Mesh oder Single) + # Step 3: arrange, cut and check (build_inlay does all three) print(t_("cli.step3")) inlay, box_w, box_d, box_h = build_inlay( - dilated_meshes, config, stable_global_bounds=stable_bounds, - individual_recess_positions=recess_positions, + dilated_meshes, config, file_names=input_paths, + individual_recess_positions=recess_positions if config.enable_finger_recesses else None, ) inlay.export(file_obj=args.output, file_type="stl") print(t_("cli.saved", path=args.output)) - # Schritt 4: Wandstärke prüfen + # Step 4: wall check print(t_("cli.step4")) - stats_3d = wall_thickness_stats_3d(inlay, config) + stats_3d = wall_thickness_stats_3d(inlay) print() - if not stats_3d["passes_min_wall"]: - print( - t_("cli.warn_thin", wall=config.wall_thickness, - measured=f"{stats_3d['min_wall_mm']:.2f}") - ) + if stats_3d["passes_min_wall"]: + print(t_("cli.success", wall=config.wall_thickness)) else: - print( - t_("cli.success", wall=config.wall_thickness) - ) + print(t_("cli.warn_thin", wall=config.wall_thickness, + measured=f"{stats_3d['min_wall_mm']:.2f}")) + for violation in stats_3d["violations"]: + print(" - " + describe_violation(violation, input_paths)) + print(t_("cli.check_failed", path=args.output, code=EXIT_CHECK_FAILED)) print("\n" + t_("cli.total_time", seconds=f"{time.perf_counter() - t_total:.1f}")) + if not stats_3d["passes_min_wall"]: + sys.exit(EXIT_CHECK_FAILED) diff --git a/tests/conftest.py b/tests/conftest.py index b02f265..ad371bf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,13 +19,17 @@ @pytest.fixture(autouse=True) -def _pin_language(): - """Pinnt die Ausgabesprache fuer jeden Test auf Englisch. - - Tests, die auf Log- oder Fehlertexte matchen, sollen nicht davon abhaengen, - welche Sprache gerade Standard ist oder ob INLAYER_LANG in der Umgebung - gesetzt ist. Die Standardsprache selbst wird in tests/test_i18n.py geprueft. +def _pin_language(monkeypatch): + """Pins the output language of every test to English. + + Tests that match log or error texts must not depend on the default + language or on INLAYER_LANG in the environment. Both are pinned: the + ContextVar for this process, the variable for the CLI subprocesses, which + inherit the environment - `INLAYER_LANG=de pytest` (as README and + compose.yaml suggest) used to fail the CLI tests. The default language + itself is tested in tests/test_i18n.py. """ + monkeypatch.setenv(i18n.ENV_VAR, "en") i18n.set_language("en") yield diff --git a/tests/geometry_probe.py b/tests/geometry_probe.py new file mode 100644 index 0000000..531ef61 --- /dev/null +++ b/tests/geometry_probe.py @@ -0,0 +1,114 @@ +"""Measures a finished inlay mesh - the test oracle for geometry invariants. + +The pipeline's own numbers (box dimensions, metadata, formulas) cannot tell +whether the printed part is right: a test that recomputes a formula passes +while the geometry is broken. These helpers only *measure* the output mesh, +exactly and independently of the code under test (manifold3d booleans, ray +casts and gap queries). They assume the inlay's box sits at [0, w] x [0, d] x +[0, h], which is where `build_inlay` puts it. +""" + +from __future__ import annotations + +import numpy as np +import trimesh +from manifold3d import Manifold, Mesh + + +def to_manifold(mesh: trimesh.Trimesh) -> Manifold: + return Manifold(Mesh( + vert_properties=np.asarray(mesh.vertices, dtype=np.float32), + tri_verts=np.asarray(mesh.faces, dtype=np.uint32), + )) + + +# The inlay's outer faces coincide with the reference box up to float32 noise; +# subtracting it from the full box leaves a skin of slivers that glues every +# pocket into one component. Shrinking the reference box by this much avoids +# that and only matters where a pocket breaks through (then a wall reads as +# 0.001 instead of 0 - still a failure against any real target). +_SKIN = 1e-3 + + +def _box(w: float, d: float, h: float) -> Manifold: + return Manifold.cube((w - 2 * _SKIN, d - 2 * _SKIN, h - 2 * _SKIN)).translate( + (_SKIN, _SKIN, _SKIN) + ) + + +def cavities(inlay: trimesh.Trimesh, w: float, d: float, h: float) -> list[Manifold]: + """The removed space (box minus inlay), one Manifold per separate pocket.""" + removed = _box(w, d, h) - to_manifold(inlay) + return [c for c in removed.decompose() if c.volume() > 1e-6] + + +def outer_walls(inlay: trimesh.Trimesh, w: float, d: float, h: float) -> dict[str, float]: + """Thinnest side and floor wall of a cuboid inlay, in mm. + + For axis-parallel walls the minimum over a pocket is exactly its bounds + distance to the box face. Negative values mean the pocket breaks through. + """ + pockets = cavities(inlay, w, d, h) + if not pockets: + return {"side": float("inf"), "floor": float("inf")} + lo = np.array([c.bounding_box()[:3] for c in pockets]) + hi = np.array([c.bounding_box()[3:] for c in pockets]) + side = min(lo[:, 0].min(), lo[:, 1].min(), w - hi[:, 0].max(), d - hi[:, 1].max()) + return {"side": float(side), "floor": float(lo[:, 2].min())} + + +def cylinder_side_wall(inlay: trimesh.Trimesh) -> float: + """Thinnest radial wall of a cylindrical inlay, in mm. + + The outer prism shows itself as vertical faces at full radius; its flat + sides (the apothem) are the closest the outside comes to the axis. Every + other vertex belongs to a pocket, the farthest one sets the wall. + """ + v = inlay.vertices + # The axis is the mean of the bottom face's corners (a regular polygon). + # Not the bounds' centre: with an odd number of sections the prism has a + # corner on one side and a flat on the other. + centre = v[v[:, 2] < inlay.bounds[0][2] + 1e-4][:, :2].mean(axis=0) + radius = np.linalg.norm(v[:, :2] - centre, axis=1) + on_rim = radius > radius.max() - 1e-3 + outer = (np.abs(inlay.face_normals[:, 2]) < 1e-6) & on_rim[inlay.faces].all(axis=1) + apothem = np.einsum( + "ij,ij->i", + inlay.triangles_center[outer][:, :2] - centre, + inlay.face_normals[outer][:, :2], + ).min() + return float(apothem - radius[~on_rim].max()) + + +def inner_gap(inlay: trimesh.Trimesh, w: float, d: float, h: float, search: float = 5.0) -> float: + """Thinnest wall between two separate pockets (inf with fewer than two). + + Gaps beyond `search` read as `search` - min_gap's cost grows with it. + """ + pockets = cavities(inlay, w, d, h) + gaps = [ + a.min_gap(b, search) + for i, a in enumerate(pockets) for b in pockets[i + 1:] + ] + return float(min(gaps)) if gaps else float("inf") + + +def shell_count(inlay: trimesh.Trimesh) -> int: + """Number of separate surfaces; more than 1 means an enclosed void.""" + return len(inlay.split(only_watertight=False)) + + +def surface_hits(inlay: trimesh.Trimesh, x: float, y: float) -> list[float]: + """Z of every surface a vertical ray through (x, y) crosses, top first.""" + top = float(inlay.bounds[1][2]) + 10.0 + bottom = float(inlay.bounds[0][2]) - 10.0 + hits = to_manifold(inlay).ray_cast((x, y, top), (x, y, bottom)) + return [float(hit.position[2]) for hit in hits] + + +def pocket_floor(inlay: trimesh.Trimesh, x: float, y: float, h: float) -> float | None: + """Z of the pocket floor below (x, y), or None if the top is closed there.""" + hits = surface_hits(inlay, x, y) + if not hits or hits[0] >= h - 1e-4: + return None + return hits[0] diff --git a/tests/test_app_helpers.py b/tests/test_app_helpers.py index dc91f0e..a97a7ff 100644 --- a/tests/test_app_helpers.py +++ b/tests/test_app_helpers.py @@ -16,40 +16,83 @@ import app_helpers -class TestRecessPositionTargets: - """Figure selection of the per-figure finger recess position control.""" +class TestResolveSelection: + """One rule for all three per-figure controls (recess, offsets, rotation).""" ALL = "Alle Figuren" # the app's untranslated sentinel def test_all_figures_reads_first_writes_every(self): - names = ["a.stl", "b.stl", "c.stl"] - ref, targets = app_helpers.recess_position_targets(self.ALL, names, self.ALL) - assert ref == "a.stl" - assert targets == names + ids = ["a", "b", "c"] + assert app_helpers.resolve_selection(self.ALL, ids, self.ALL) == (self.ALL, "a", ids) def test_single_selection_reads_and_writes_that_figure(self): - names = ["a.stl", "b.stl"] - ref, targets = app_helpers.recess_position_targets("b.stl", names, self.ALL) - assert ref == "b.stl" - assert targets == ["b.stl"] - - def test_stale_selection_falls_back_to_the_first_figure(self): - """A figure removed from the upload must not raise on the next rerun.""" - names = ["a.stl"] - ref, targets = app_helpers.recess_position_targets("gone.stl", names, self.ALL) - assert ref == "a.stl" - assert targets == ["a.stl"] + assert app_helpers.resolve_selection("b", ["a", "b"], self.ALL) == ("b", "b", ["b"]) + + def test_removed_figure_falls_back_to_all(self): + """The selection itself is repaired, so the selectbox never sees a + value that is no longer among its options.""" + assert app_helpers.resolve_selection("gone", ["a", "b"], self.ALL) == (self.ALL, "a", ["a", "b"]) + + def test_first_figure_under_all_follows_the_upload(self): + """Under "all figures" the reference is whatever figure is first now.""" + assert app_helpers.resolve_selection(self.ALL, ["b"], self.ALL)[1] == "b" def test_returned_target_list_is_a_copy(self): - """The caller writes through the list; it must not alias fig_names.""" - names = ["a.stl", "b.stl"] - _, targets = app_helpers.recess_position_targets(self.ALL, names, self.ALL) - targets.append("c.stl") - assert names == ["a.stl", "b.stl"] + """The caller writes through the list; it must not alias fig_ids.""" + ids = ["a", "b"] + app_helpers.resolve_selection(self.ALL, ids, self.ALL)[2].append("c") + assert ids == ["a", "b"] def test_empty_figure_list_raises(self): with pytest.raises(ValueError): - app_helpers.recess_position_targets(self.ALL, [], self.ALL) + app_helpers.resolve_selection(self.ALL, [], self.ALL) + + +class TestFigureLabels: + def test_repeated_names_get_a_counter(self): + assert app_helpers.figure_labels(["model.stl", "a.stl", "model.stl"]) == [ + "model.stl", "a.stl", "model.stl (2)" + ] + + def test_empty(self): + assert app_helpers.figure_labels([]) == [] + + +class TestAppliedFigureParams: + STORED = { + "a": {**app_helpers.FIGURE_DEFAULTS, "offset_x": 5.0, "rot_z": 90.0, "finger_recess_position": 0.5}, + "b": dict(app_helpers.FIGURE_DEFAULTS), + } + + def test_values_per_figure_in_upload_order(self): + applied = app_helpers.applied_figure_params(self.STORED, ["b", "a"], True, True, True) + assert applied[1] == {"offset": (5.0, 0.0, 0.0), "rotation": (0.0, 0.0, 90.0), + "recess_position": 0.5} + assert applied[0]["offset"] == (0.0, 0.0, 0.0) + + def test_disabled_features_count_as_zero(self): + (a,) = app_helpers.applied_figure_params(self.STORED, ["a"], False, False, False) + assert a == {"offset": (0.0, 0.0, 0.0), "rotation": (0.0, 0.0, 0.0), "recess_position": 0.0} + + def test_unknown_figure_gets_the_defaults(self): + (x,) = app_helpers.applied_figure_params({}, ["new"], True, True, True) + assert x["offset"] == (0.0, 0.0, 0.0) and x["recess_position"] == 0.0 + + +class TestPreviewCopy: + def test_never_the_input_and_no_metadata(self): + """Below the face budget decimate_mesh returns its input - the cache + then held the whole inlay, metadata and all.""" + box = trimesh.creation.box(extents=[1, 1, 1]) + box.metadata["wall_check"] = {"big": "payload"} + out = app_helpers.preview_copy(box, 10000) + assert out is not box + assert out.metadata == {} + assert len(out.faces) == len(box.faces) + + def test_decimates_above_the_budget(self): + sphere = trimesh.creation.icosphere(subdivisions=4) + assert len(app_helpers.preview_copy(sphere, 500).faces) < len(sphere.faces) class TestFileHash: @@ -179,29 +222,51 @@ class TestLoadPreviewMesh: def test_loads_stl_bytes(self, tmp_path): box = trimesh.creation.box(extents=[10, 10, 10]) data = cast(bytes, box.export(file_type="stl")) - out = app_helpers.load_preview_mesh(data, 1.0) + out = app_helpers.load_preview_mesh(data, 1.0, "box.stl") assert len(out.faces) > 0 def test_scale_is_applied(self): box = trimesh.creation.box(extents=[10, 10, 10]) data = cast(bytes, box.export(file_type="stl")) - out = app_helpers.load_preview_mesh(data, 2.0) + out = app_helpers.load_preview_mesh(data, 2.0, "box.stl") # Skalierung verdoppelt die Kantenlaenge. assert out.extents[0] == pytest.approx(20.0, rel=1e-3) def test_scale_one_leaves_size(self): box = trimesh.creation.box(extents=[10, 10, 10]) data = cast(bytes, box.export(file_type="stl")) - out = app_helpers.load_preview_mesh(data, 1.0) + out = app_helpers.load_preview_mesh(data, 1.0, "box.stl") assert out.extents[0] == pytest.approx(10.0, rel=1e-3) def test_large_mesh_is_decimated(self): sphere = trimesh.creation.icosphere(subdivisions=6) # 81920 Faces assert len(sphere.faces) > app_helpers.PREVIEW_FACE_BUDGET data = cast(bytes, sphere.export(file_type="stl")) - out = app_helpers.load_preview_mesh(data, 1.0) + out = app_helpers.load_preview_mesh(data, 1.0, "box.stl") assert len(out.faces) < len(sphere.faces) + @pytest.mark.parametrize( + "data", + [b"", bytes(84), b"solid x\nendsolid x\n", bytes(range(256)) * 2], + ids=["zero-bytes", "binary-header-only", "ascii-no-facets", "garbage"], + ) + def test_empty_or_garbled_upload_names_the_file(self, data): + """An empty mesh used to crash the preview on `mesh.bounds[0][0]`.""" + with pytest.raises(ValueError, match="upload.stl"): + app_helpers.load_preview_mesh(data, 1.0, "upload.stl") + + +class TestBytesHash: + def test_matches_file_hash_of_the_same_content(self, tmp_path): + data = bytes(range(256)) * 100 + p = tmp_path / "x.bin" + p.write_bytes(data) + assert app_helpers.bytes_hash(data) == app_helpers.file_hash(str(p)) + + def test_same_size_different_content_differs(self): + """Name and size were the cache key; two 684-byte STLs collided.""" + assert app_helpers.bytes_hash(b"a" * 684) != app_helpers.bytes_hash(b"b" * 684) + class TestSceneLayout: def test_contains_expected_keys(self): diff --git a/tests/test_app_render.py b/tests/test_app_render.py index 136bf26..64e26e9 100644 --- a/tests/test_app_render.py +++ b/tests/test_app_render.py @@ -10,9 +10,14 @@ from __future__ import annotations +import ast +import base64 +import json from pathlib import Path +import numpy as np import pytest +import trimesh from streamlit.testing.v1 import AppTest import i18n @@ -27,6 +32,90 @@ def _run(lang: str) -> AppTest: return at +def _stl(extents) -> bytes: + return trimesh.creation.box(extents=extents).export(file_type="stl") + + +def _upload(at: AppTest, files: list[tuple[str, bytes]]) -> AppTest: + at.file_uploader[0].set_value([(name, data, "model/stl") for name, data in files]) + at.run() + assert not at.exception, [str(e.value) for e in at.exception] + return at + + +def _checkbox(at: AppTest, key: str): + label = i18n.TRANSLATIONS[key][i18n.get_language()] + return next(c for c in at.sidebar.checkbox if c.label == label) + + +def _warned(at: AppTest, key: str) -> bool: + """Whether a warning with that text is shown (Streamlit strips a leading emoji).""" + text = i18n.TRANSLATIONS[key][i18n.get_language()] + return any(w.value.strip() and w.value.strip() in text for w in at.warning) + + +def _trace_extents(at: AppTest) -> dict[str, float]: + """X extent of every trace in the first 3D chart, by trace name.""" + spec = json.loads(at.get("plotly_chart")[0].proto.spec) + extents = {} + for trace in spec["data"]: + x = trace["x"] + if isinstance(x, dict): # plotly ships numpy arrays base64-encoded + x = np.frombuffer(base64.b64decode(x["bdata"]), dtype=x["dtype"]) + extents[trace["name"]] = float(np.ptp(np.asarray(x, dtype=float))) + return extents + + +class TestUploadRobustness: + def test_broken_file_is_skipped_with_a_warning(self): + """One empty upload used to crash the preview of every file (review B18).""" + at = _upload(_run("en"), [("a.stl", _stl([10, 10, 10])), ("empty.stl", b"")]) + assert any("empty.stl" in w.value for w in at.warning) + assert list(_trace_extents(at)) == ["a.stl"] + + +class TestCacheIdentity: + """Process-wide caches are keyed by content, never by name and size.""" + + def test_sessions_do_not_see_each_others_upload(self): + """Two 12-triangle STLs share name and size (684 bytes) - review B20.""" + first, second = _stl([10, 10, 10]), _stl([20, 5, 5]) + assert len(first) == len(second) + _upload(_run("en"), [("model.stl", first)]) + other_session = _upload(_run("en"), [("model.stl", second)]) + assert _trace_extents(other_session)["model.stl"] == pytest.approx(20.0) + + def test_replacing_a_file_of_the_same_size_marks_the_result_stale(self): + at = _upload(_run("en"), [("model.stl", _stl([10, 10, 10]))]) + next(s for s in at.sidebar.slider + if s.label == i18n.TRANSLATIONS["app.voxel_pitch.label"]["en"]).set_value(1.0).run() + at.button[0].click().run() + assert not at.exception, [str(e.value) for e in at.exception] + assert not _warned(at, "app.results.stale") + _upload(at, [("model.stl", _stl([20, 5, 5]))]) + assert _warned(at, "app.results.stale") + + +class TestRotationStepSurvivesHiding: + """Streamlit drops a widget's state while it is not rendered (review B19). + + The rotation step fell back to 45° when the section was hidden, a stored + 350° then exceeded the slider's max of 315° and every rerun raised. + """ + + def test_hide_and_show_keeps_step_and_angle(self): + at = _run("en") + _checkbox(at, "app.manual_rotations.label").check().run() + next(s for s in at.sidebar.selectbox if s.key == "_w_rot_step").set_value(10.0).run() + next(s for s in at.sidebar.slider if s.key == "_sl_rot_x").set_value(350.0).run() + _checkbox(at, "app.manual_rotations.label").uncheck().run() + _checkbox(at, "app.manual_rotations.label").check().run() + assert not at.exception, [str(e.value) for e in at.exception] + assert next(s for s in at.sidebar.selectbox if s.key == "_w_rot_step").value == 10.0 + assert next(s for s in at.sidebar.slider if s.key == "_sl_rot_x").value == 350.0 + assert at.button, "the run button must still render" + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) def test_app_renders_without_exception(lang): at = _run(lang) @@ -66,133 +155,223 @@ def test_run_button_label_follows_language(): assert _run("en").button[0].label == i18n.TRANSLATIONS["app.run.button"]["en"] -class TestFingerRecessPositionWidget: - """The recess position control writes into the per-figure session state. +RECESS_KEY = "_sl_finger_recess_position" +ALL = "Alle Figuren" # the app's untranslated sentinel - Only the single-figure path is reachable here: AppTest cannot drive the - file uploader, so the figure selectbox (which needs more than one upload) - is covered by app_helpers.recess_position_targets instead. - """ - KEY = "_sl_finger_recess_position" - FALLBACK_FIG = "figur.stl" +def _ids(at: AppTest) -> list[str]: + """File ids of the current uploads, in upload order.""" + return list(at.session_state["_hash_by_file_id"]) - def _enabled_app(self) -> AppTest: - at = _run("en") - checkbox = next( - c for c in at.sidebar.checkbox - if c.label == i18n.TRANSLATIONS["app.finger.enable.label"]["en"] - ) - checkbox.check().run() + +def _widget(at: AppTest, kind: str, key: str): + return next(w for w in getattr(at.sidebar, kind) if w.key == key) + + +def _stored(at: AppTest, index: int, name: str): + return at.session_state["fig_offsets_dict"][_ids(at)[index]][name] + + +def _two_figures(**flags) -> AppTest: + at = _upload(_run("en"), [("cube.stl", _stl([10, 10, 10])), ("sphere.stl", _stl([8, 8, 8]))]) + for key in flags: + _widget(at, "checkbox", key).check().run() + assert not at.exception, [str(e.value) for e in at.exception] + return at + + +def test_every_widget_has_a_fixed_key(): + """Streamlit derives an unkeyed widget's identity from its translated + label: a language switch created new widgets, the uploads vanished and + every setting fell back to its default (review R15). Checked statically, + so a new widget cannot slip through.""" + widgets = {"slider", "number_input", "checkbox", "selectbox", "file_uploader", "radio", + "text_input", "toggle", "multiselect", "button", "download_button"} + tree = ast.parse(Path(APP).read_text(encoding="utf-8")) + unkeyed = [ + f"line {node.lineno}: {node.func.attr}" + for node in ast.walk(tree) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in widgets and not any(k.arg == "key" for k in node.keywords) + ] + assert not unkeyed + + +class TestLanguageSwitchKeepsState: + def test_values_and_uploads_survive(self): + """Review B21: switching the language reset values and uploads.""" + at = _upload(_run("en"), [("cube.stl", _stl([10, 10, 10]))]) + _widget(at, "slider", "clearance").set_value(1.0).run() + _widget(at, "slider", "wall_thickness").set_value(3.5).run() + _widget(at, "checkbox", "finger_enabled").check().run() + _widget(at, "checkbox", "manual_rotations").check().run() + _widget(at, "selectbox", "ui_lang").set_value("de").run() assert not at.exception, [str(e.value) for e in at.exception] - return at + assert _widget(at, "slider", "clearance").value == 1.0 + assert _widget(at, "slider", "wall_thickness").value == 3.5 + assert _widget(at, "checkbox", "finger_enabled").value is True + assert _widget(at, "checkbox", "manual_rotations").value is True + assert len(_ids(at)) == 1 + + def test_translated_selectboxes_keep_their_value(self): + """Streamlit sends a selectbox value as its *label*. After a switch the + old label matches no option: the recess axis came back as the string + "left/right" (a crash on the next run), box shape and layout fell back + to their defaults.""" + at = _two_figures(finger_enabled=True) + for key, value in (("_w_finger_axis", "y"), ("_w_box_shape", "cylinder"), + ("_w_layout_style", "vertical")): + _widget(at, "selectbox", key).set_value(value).run() + _widget(at, "selectbox", "ui_lang").set_value("de").run() + _widget(at, "checkbox", "parallel").check().run() # any further rerun + assert not at.exception, [str(e.value) for e in at.exception] + assert _widget(at, "selectbox", "_w_finger_axis").value == "y" + assert _widget(at, "selectbox", "_w_box_shape").value == "cylinder" + assert _widget(at, "selectbox", "_w_layout_style").value == "vertical" + + +class TestFingerRecessPosition: + """The recess position is stored per upload; one slider shows the selected one.""" def test_slider_only_exists_with_recesses_enabled(self): - assert not [s for s in _run("en").sidebar.slider if s.key == self.KEY] - assert [s for s in self._enabled_app().sidebar.slider if s.key == self.KEY] + at = _run("en") + assert not [s for s in at.sidebar.slider if s.key == RECESS_KEY] + _widget(at, "checkbox", "finger_enabled").check().run() + assert [s for s in at.sidebar.slider if s.key == RECESS_KEY] - def test_slider_writes_the_fraction_into_the_figure_state(self): - at = self._enabled_app() - slider = next(s for s in at.sidebar.slider if s.key == self.KEY) - slider.set_value(60).run() - assert not at.exception, [str(e.value) for e in at.exception] - stored = at.session_state["fig_offsets_dict"][self.FALLBACK_FIG] + def test_slider_writes_the_fraction_and_starts_centred(self): + at = _run("en") + _widget(at, "checkbox", "finger_enabled").check().run() + assert _widget(at, "slider", RECESS_KEY).value == 0 + _widget(at, "slider", RECESS_KEY).set_value(60).run() # Percent in the UI, fraction in the pipeline - assert stored["finger_recess_position"] == pytest.approx(0.6) - - def test_slider_starts_centred(self): - at = self._enabled_app() - slider = next(s for s in at.sidebar.slider if s.key == self.KEY) - assert slider.value == 0 - stored = at.session_state["fig_offsets_dict"][self.FALLBACK_FIG] - assert stored["finger_recess_position"] == pytest.approx(0.0) - - -class TestFingerRecessPositionPerFigure: - """Two uploads, two independent grip positions in the sidebar.""" - - KEY = "_sl_finger_recess_position" - SELECT = "selected_recess_fig" - ALL = "Alle Figuren" # the app's untranslated sentinel - - def _app_with_two_figures(self, cube_stl_path, sphere_stl_path) -> AppTest: - at = AppTest.from_file(APP, default_timeout=120) - at.session_state["ui_lang"] = "en" - at.run() - at.file_uploader[0].set_value( - [ - ("cube.stl", Path(cube_stl_path).read_bytes(), "model/stl"), - ("sphere.stl", Path(sphere_stl_path).read_bytes(), "model/stl"), - ] - ) - at.run() - checkbox = next( - c for c in at.sidebar.checkbox - if c.label == i18n.TRANSLATIONS["app.finger.enable.label"]["en"] - ) - checkbox.check().run() - assert not at.exception, [str(e.value) for e in at.exception] - return at + assert at.session_state["fig_offsets_dict"]["__fallback__"]["finger_recess_position"] == 0.6 - @staticmethod - def _stored(at: AppTest, name: str) -> float: - return at.session_state["fig_offsets_dict"][name]["finger_recess_position"] - - def test_selection_appears_only_with_several_figures(self, cube_stl_path, sphere_stl_path): - single = _run("en") - assert not [s for s in single.sidebar.selectbox if s.key == self.SELECT] - at = self._app_with_two_figures(cube_stl_path, sphere_stl_path) - selector = next(s for s in at.sidebar.selectbox if s.key == self.SELECT) + def test_selection_only_with_several_figures(self): + assert not [s for s in _run("en").sidebar.selectbox if s.key == "selected_recess_fig"] + at = _two_figures(finger_enabled=True) + selector = _widget(at, "selectbox", "selected_recess_fig") assert list(selector.options) == ["All figures", "cube.stl", "sphere.stl"] - def test_value_is_stored_for_the_selected_figure_only(self, cube_stl_path, sphere_stl_path): - at = self._app_with_two_figures(cube_stl_path, sphere_stl_path) - next(s for s in at.sidebar.selectbox if s.key == self.SELECT).set_value("sphere.stl").run() - next(s for s in at.sidebar.slider if s.key == self.KEY).set_value(40).run() - assert not at.exception, [str(e.value) for e in at.exception] - assert self._stored(at, "sphere.stl") == pytest.approx(0.4) - assert self._stored(at, "cube.stl") == pytest.approx(0.0) - - def test_switching_figures_reloads_the_stored_value(self, cube_stl_path, sphere_stl_path): - at = self._app_with_two_figures(cube_stl_path, sphere_stl_path) - select = lambda name: next( # noqa: E731 - one-liner keeps the steps readable - s for s in at.sidebar.selectbox if s.key == self.SELECT - ).set_value(name).run() - slider = lambda: next(s for s in at.sidebar.slider if s.key == self.KEY) # noqa: E731 - - select("sphere.stl") - slider().set_value(40).run() - select("cube.stl") - # The cube was never touched, so the slider shows its own value again - assert slider().value == 0 - slider().set_value(-60).run() - assert self._stored(at, "cube.stl") == pytest.approx(-0.6) - assert self._stored(at, "sphere.stl") == pytest.approx(0.4) - - select("sphere.stl") - assert slider().value == 40 - - def test_all_figures_writes_every_value(self, cube_stl_path, sphere_stl_path): - at = self._app_with_two_figures(cube_stl_path, sphere_stl_path) - next(s for s in at.sidebar.selectbox if s.key == self.SELECT).set_value(self.ALL).run() - next(s for s in at.sidebar.slider if s.key == self.KEY).set_value(25).run() - assert not at.exception, [str(e.value) for e in at.exception] - assert self._stored(at, "cube.stl") == pytest.approx(0.25) - assert self._stored(at, "sphere.stl") == pytest.approx(0.25) - - def test_per_figure_values_survive_an_unrelated_rerun(self, cube_stl_path, sphere_stl_path): - """A rerun with "all figures" selected must not flatten stored values.""" - at = self._app_with_two_figures(cube_stl_path, sphere_stl_path) - next(s for s in at.sidebar.selectbox if s.key == self.SELECT).set_value("sphere.stl").run() - next(s for s in at.sidebar.slider if s.key == self.KEY).set_value(80).run() - next(s for s in at.sidebar.selectbox if s.key == self.SELECT).set_value(self.ALL).run() - # Move an unrelated slider - the recess values must stay untouched - radius = next( - s for s in at.sidebar.slider - if s.label == i18n.TRANSLATIONS["app.finger.radius.label"]["en"] - ) - radius.set_value(10.0).run() + def test_value_is_stored_for_the_selected_figure_only(self): + at = _two_figures(finger_enabled=True) + _widget(at, "selectbox", "selected_recess_fig").select_index(2).run() + _widget(at, "slider", RECESS_KEY).set_value(40).run() + assert _stored(at, 1, "finger_recess_position") == pytest.approx(0.4) + assert _stored(at, 0, "finger_recess_position") == 0.0 + + def test_switching_figures_reloads_the_stored_value(self): + at = _two_figures(finger_enabled=True) + select = lambda i: _widget(at, "selectbox", "selected_recess_fig").select_index(i).run() # noqa: E731 + select(2) + _widget(at, "slider", RECESS_KEY).set_value(40).run() + select(1) + assert _widget(at, "slider", RECESS_KEY).value == 0 + _widget(at, "slider", RECESS_KEY).set_value(-60).run() + select(2) + assert _widget(at, "slider", RECESS_KEY).value == 40 + assert _stored(at, 0, "finger_recess_position") == pytest.approx(-0.6) + + def test_all_figures_writes_every_value_and_survives_reruns(self): + at = _two_figures(finger_enabled=True) + _widget(at, "selectbox", "selected_recess_fig").select_index(2).run() + _widget(at, "slider", RECESS_KEY).set_value(80).run() + _widget(at, "selectbox", "selected_recess_fig").set_value(ALL).run() + # An unrelated rerun must not flatten the stored values + _widget(at, "slider", "finger_radius").set_value(10.0).run() + assert _stored(at, 1, "finger_recess_position") == pytest.approx(0.8) + _widget(at, "slider", RECESS_KEY).set_value(25).run() + assert _stored(at, 0, "finger_recess_position") == pytest.approx(0.25) + assert _stored(at, 1, "finger_recess_position") == pytest.approx(0.25) + + +class TestSlidersFollowTheUploads: + """After the file list changes a slider shows what the pipeline will use + (review R14/B22). Before, it kept the previous figure's value while the + pipeline used the stored one.""" + + def test_recess_slider_after_replacing_the_file(self): + at = _upload(_run("en"), [("a.stl", _stl([10, 10, 10]))]) + _widget(at, "checkbox", "finger_enabled").check().run() + _widget(at, "slider", RECESS_KEY).set_value(60).run() + _upload(at, [("b.stl", _stl([20, 5, 5]))]) + assert _widget(at, "slider", RECESS_KEY).value == 0 + assert _stored(at, 0, "finger_recess_position") == 0.0 + + @pytest.mark.parametrize( + "flag,select,axis,value", + [("manual_offsets", "selected_fig", "offset_z", 20.0), + ("manual_rotations", "selected_rot_fig", "rot_z", 90.0)], + ) + def test_axis_slider_after_removing_the_selected_figure(self, flag, select, axis, value): + at = _two_figures(**{flag: True}) + _widget(at, "selectbox", select).select_index(2).run() + _widget(at, "slider", f"_sl_{axis}").set_value(value).run() + assert _stored(at, 1, axis) == value + _upload(at, [("cube.stl", _stl([10, 10, 10]))]) + assert _widget(at, "slider", f"_sl_{axis}").value == _stored(at, 0, axis) == 0.0 + + +class TestSettingsPerUpload: + """Settings belong to an upload, not to a file name (review N7/B24).""" + + def test_two_files_with_the_same_name_move_separately(self): + at = _upload(_run("en"), [("model.stl", _stl([10, 10, 10])), ("model.stl", _stl([20, 5, 5]))]) + _widget(at, "checkbox", "manual_offsets").check().run() + selector = _widget(at, "selectbox", "selected_fig") + assert list(selector.options) == ["All figures", "model.stl", "model.stl (2)"] + selector.select_index(2).run() + _widget(at, "slider", "_sl_offset_x").set_value(30.0).run() + assert _stored(at, 1, "offset_x") == 30.0 + assert _stored(at, 0, "offset_x") == 0.0 + + def test_upload_again_starts_from_the_defaults(self): + at = _upload(_run("en"), [("a.stl", _stl([10, 10, 10]))]) + _widget(at, "checkbox", "manual_rotations").check().run() + _widget(at, "slider", "_sl_rot_x").set_value(90.0).run() + _upload(at, []) + _upload(at, [("a.stl", _stl([10, 10, 10]))]) + assert _stored(at, 0, "rot_x") == 0.0 + assert _widget(at, "slider", "_sl_rot_x").value == 0.0 + + +class TestGapFollowsWallThickness: + def test_until_the_user_sets_a_gap(self): + """Review N8/B25: the gap was copied from the wall thickness once.""" + at = _two_figures() + _widget(at, "slider", "wall_thickness").set_value(4.0).run() + assert _widget(at, "slider", "_sl_figure_gap").value == 4.0 + _widget(at, "slider", "_sl_figure_gap").set_value(3.0).run() + _widget(at, "slider", "wall_thickness").set_value(5.0).run() + assert _widget(at, "slider", "_sl_figure_gap").value == 3.0 + assert at.session_state["figure_gap"] == 3.0 + + +class TestResult: + @staticmethod + def _generate(at: AppTest) -> AppTest: + _widget(at, "slider", "voxel_pitch").set_value(1.0).run() + at.button[0].click().run() assert not at.exception, [str(e.value) for e in at.exception] - assert self._stored(at, "sphere.stl") == pytest.approx(0.8) - assert self._stored(at, "cube.stl") == pytest.approx(0.0) + return at + def test_switching_the_recess_selection_is_not_a_change(self): + """Review N6/B23: only showing another figure marked the result stale.""" + at = self._generate(_two_figures(finger_enabled=True)) + assert not _warned(at, "app.results.stale") + _widget(at, "selectbox", "selected_recess_fig").select_index(2).run() + assert not _warned(at, "app.results.stale") + + def test_parallel_run_through_the_shared_thread_pool(self): + """The app runs its per-figure steps through inlayer._parallel_map with + the Streamlit context attached (worker_init) - no pool of its own.""" + res = self._generate(_two_figures(parallel=True)).session_state["result"] + assert res["stats_3d"]["passes_min_wall"] is True + + def test_session_keeps_only_slim_geometry(self): + """Review N20: the full inlay (with its cavity grid) and the dilated + figures sat in every session's state.""" + res = self._generate(_two_figures()).session_state["result"] + assert not {"inlay", "fig_offsets", "xy_translations", "z_offsets"} & set(res) + assert res["inlay_viz"].metadata == {} + assert len(res["placements"]) == 2 diff --git a/tests/test_arrange_figures.py b/tests/test_arrange_figures.py deleted file mode 100644 index d8d1d1c..0000000 --- a/tests/test_arrange_figures.py +++ /dev/null @@ -1,427 +0,0 @@ -"""Tests fuer inlayer.arrange_figures (Shelf-Packing-Algorithmus).""" - -from __future__ import annotations - -import numpy as np -import pytest -import trimesh - -import inlayer - - -class TestArrangeFiguresSingleMesh: - def test_single_mesh_returns_copy(self, cube_mesh): - """Ein einzelnes Mesh wird als unveraenderte Kopie zurueckgegeben.""" - result = inlayer.arrange_figures([cube_mesh], gap=2.0) - assert len(result) == 1 - # Kopie, nicht dasselbe Objekt - assert result[0] is not cube_mesh - # Gleiche Geometrie - np.testing.assert_allclose( - result[0].extents, cube_mesh.extents, atol=1e-6 - ) - - -class TestArrangeFiguresTwoMeshes: - def test_no_overlap(self, cube_mesh, sphere_mesh): - """Zwei Meshes duerfen nach Anordnung nicht ueberlappen.""" - result = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=2.0) - assert len(result) == 2 - # Bounding-Boxes extrahieren - bb0_min, bb0_max = result[0].bounds - bb1_min, bb1_max = result[1].bounds - # Mindestens in X oder Y muss es keine Ueberlappung geben - no_x_overlap = bb0_max[0] <= bb1_min[0] or bb1_max[0] <= bb0_min[0] - no_y_overlap = bb0_max[1] <= bb1_min[1] or bb1_max[1] <= bb0_min[1] - assert no_x_overlap or no_y_overlap, ( - f"Bounding-Boxes ueberlappen: {result[0].bounds} vs {result[1].bounds}" - ) - - -class TestArrangeFiguresGap: - def test_gap_respected(self, cube_mesh, sphere_mesh): - """Der Abstand zwischen Meshes muss mindestens 'gap' betragen.""" - gap = 3.0 - result = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=gap) - - # Abstand in X zwischen den Bounding-Boxes - bb0_max_x = result[0].bounds[1][0] - bb1_min_x = result[1].bounds[0][0] - bb1_max_x = result[1].bounds[1][0] - bb0_min_x = result[0].bounds[0][0] - - # Eines der beiden muss rechts bzw. links liegen - if bb1_min_x >= bb0_max_x: - actual_gap_x = bb1_min_x - bb0_max_x - assert actual_gap_x >= gap - 0.01, ( - f"X-Gap {actual_gap_x:.2f} < {gap}" - ) - elif bb0_min_x >= bb1_max_x: - actual_gap_x = bb0_min_x - bb1_max_x - assert actual_gap_x >= gap - 0.01, ( - f"X-Gap {actual_gap_x:.2f} < {gap}" - ) - - -class TestArrangeFiguresThreeMeshes: - def test_three_meshes_shelf_layout(self, cube_mesh, sphere_mesh, cylinder_mesh): - """Drei verschieden grosse Meshes werden ohne Ueberlappung angeordnet.""" - result = inlayer.arrange_figures( - [cube_mesh, sphere_mesh, cylinder_mesh], gap=2.0 - ) - assert len(result) == 3 - # Keine Ueberlappung: paarweise pruefen - for i in range(len(result)): - for j in range(i + 1, len(result)): - bi_min, bi_max = result[i].bounds - bj_min, bj_max = result[j].bounds - no_x = bi_max[0] <= bj_min[0] + 0.01 or bj_max[0] <= bi_min[0] + 0.01 - no_y = bi_max[1] <= bj_min[1] + 0.01 or bj_max[1] <= bi_min[1] + 0.01 - assert no_x or no_y, ( - f"Figur {i} und {j} ueberlappen: " - f"{result[i].bounds} vs {result[j].bounds}" - ) - - -class TestArrangeFiguresZPosition: - def test_z_position_preserved(self, cube_mesh, sphere_mesh): - """Z-Positionen der Meshes bleiben unveraendert.""" - meshes = [cube_mesh, sphere_mesh] - original_z_bounds = [(m.bounds[0][2], m.bounds[1][2]) for m in meshes] - - result = inlayer.arrange_figures(meshes, gap=2.0) - - for i, m in enumerate(result): - orig_zmin, orig_zmax = original_z_bounds[i] - assert m.bounds[0][2] == pytest.approx(orig_zmin, abs=1e-6), ( - f"Figur {i}: Z-Min hat sich geaendert" - ) - assert m.bounds[1][2] == pytest.approx(orig_zmax, abs=1e-6), ( - f"Figur {i}: Z-Max hat sich geaendert" - ) - - -class TestArrangeFiguresSorting: - def test_sorted_by_area(self): - """Groesstes Mesh (nach XY-Flaeche) wird zuerst platziert (links oben).""" - small = trimesh.creation.box(extents=[3.0, 3.0, 5.0]) - large = trimesh.creation.box(extents=[10.0, 10.0, 5.0]) - - # Reihenfolge: small zuerst, large danach - result = inlayer.arrange_figures([small, large], gap=2.0) - # large (Index 1 im Input) muss links (kleinstes X) platziert sein - assert result[1].bounds[0][0] <= result[0].bounds[0][0], ( - "Groesseres Mesh sollte weiter links platziert werden" - ) - - -class TestArrangeFiguresLayoutStyles: - def test_horizontal_layout_positions_sequential_in_x(self, cube_mesh, sphere_mesh): - """Prueft, ob der horizontale Layoutstil die Figuren sequentiell auf der X-Achse anordnet.""" - result = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=5.0, layout_style="horizontal") - assert len(result) == 2 - # Das zweite Mesh muss rechts vom ersten liegen - bb0_max_x = result[0].bounds[1][0] - bb1_min_x = result[1].bounds[0][0] - assert bb1_min_x >= bb0_max_x + 4.99 - - def test_horizontal_layout_aligns_bottoms_flush_in_y(self, cube_mesh, cylinder_mesh): - """Prüft, ob der horizontale Layoutstil die Unterkanten aller Figuren bündig auf Y = 0 ausrichtet und aufsteigend sortiert.""" - # cube_mesh (10x10=100) ist größer als cylinder_mesh (8x8=64). Wir übergeben cube_mesh zuerst. - result = inlayer.arrange_figures( - [cube_mesh, cylinder_mesh], - gap=5.0, - layout_style="horizontal", - reference_meshes=[cube_mesh, cylinder_mesh] - ) - assert len(result) == 2 - # Unterkanten der Referenzen (Y-Min) müssen bündig auf 0.0 liegen - assert result[0].bounds[0][1] == pytest.approx(0.0, abs=1e-6) - assert result[1].bounds[0][1] == pytest.approx(0.0, abs=1e-6) - - # Da cylinder_mesh (Index 1) kleiner ist, muss es räumlich links von cube_mesh (Index 0) platziert sein - assert result[1].bounds[0][0] < result[0].bounds[0][0] - - def test_vertical_layout_positions_sequential_in_y(self, cube_mesh, sphere_mesh): - """Prueft, ob der vertikale Layoutstil die Figuren sequentiell auf der Y-Achse anordnet.""" - result = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=5.0, layout_style="vertical") - assert len(result) == 2 - # Das zweite Mesh muss oberhalb (in Y) des ersten liegen - bb0_max_y = result[0].bounds[1][1] - bb1_min_y = result[1].bounds[0][1] - assert bb1_min_y >= bb0_max_y + 4.99 - - -class TestArrangeFiguresErrors: - def test_empty_list_raises(self): - """Leere Liste muss ValueError ausloesen.""" - with pytest.raises(ValueError, match="At least one mesh"): - inlayer.arrange_figures([], gap=2.0) - - -class TestArrangeFiguresRotationStability: - def test_sorting_reference_meshes_keeps_order_stable(self, cube_mesh, sphere_mesh): - """Prüft, ob die Verwendung von sorting_reference_meshes die Sortierung stabil hält, selbst wenn eine Figur rotiert wird.""" - rotated_sphere = sphere_mesh.copy() - Rz = trimesh.transformations.rotation_matrix(np.radians(45.0), [0, 0, 1]) - rotated_sphere.apply_transform(Rz) - - # Anordnung mit Sortierreferenz (unrotierte Originale) - stable_result = inlayer.arrange_figures( - [cube_mesh, rotated_sphere], - gap=2.0, - layout_style="compact", - reference_meshes=[cube_mesh, rotated_sphere], - sorting_reference_meshes=[cube_mesh, sphere_mesh] - ) - - # Da cube_mesh die größere unrotierte Fläche hat, muss es links (kleineres X) platziert sein - assert stable_result[0].bounds[0][0] <= stable_result[1].bounds[0][0] - - def test_box_width_parameter_limits_target_width(self, cube_mesh, sphere_mesh, cylinder_mesh): - """Prüft, ob der Parameter box_width in arrange_figures einfließt und das Layout in eine Zeile zwingt.""" - result = inlayer.arrange_figures( - [cube_mesh, sphere_mesh, cylinder_mesh], - gap=2.0, - layout_style="compact", - box_width=150.0 - ) - - # Da box_width ausreichend groß ist, sollten alle drei Meshes in einer Reihe nebeneinander liegen (Y-Unterkante auf 0) - for m in result: - assert m.bounds[0][1] == pytest.approx(0.0, abs=1e-2) - - -class TestArrangeFiguresFingerRecesses: - def test_finger_radius_expands_bounds(self, cube_mesh, sphere_mesh): - """Prüft, ob ein übergebener finger_radius den Abstand zwischen zwei angeordneten Figuren in X-Richtung erhöht.""" - gap = 2.0 - finger_radius = 5.0 - - # Anordnung ohne Fingermulden - res_normal = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=gap, layout_style="horizontal") - dx_normal = res_normal[0].bounds[1][0] - res_normal[1].bounds[0][0] - - # Anordnung mit Fingermulden - res_finger = inlayer.arrange_figures([cube_mesh, sphere_mesh], gap=gap, layout_style="horizontal", finger_radius=finger_radius) - - # Bestimme X-Abstand zwischen den Original-Bounding-Boxes nach der Transformation - # Das links platzierte Mesh (kleineres X) und das rechts platzierte Mesh - sorted_normal = sorted(res_normal, key=lambda m: m.bounds[0][0]) - sorted_finger = sorted(res_finger, key=lambda m: m.bounds[0][0]) - - dist_normal = sorted_normal[1].bounds[0][0] - sorted_normal[0].bounds[1][0] - dist_finger = sorted_finger[1].bounds[0][0] - sorted_finger[0].bounds[1][0] - - # Der Abstand mit Fingermulden muss um genau 2 * finger_radius größer sein als der normale Abstand - assert dist_finger >= dist_normal + 2 * finger_radius - 0.01 - - def test_finger_axis_y_expands_bounds_in_y(self, cube_mesh, sphere_mesh): - """Bei finger_axis='y' erweitert der finger_radius den Abstand in Y statt in X.""" - gap = 2.0 - finger_radius = 5.0 - - res_normal = inlayer.arrange_figures( - [cube_mesh, sphere_mesh], gap=gap, layout_style="vertical" - ) - res_finger = inlayer.arrange_figures( - [cube_mesh, sphere_mesh], gap=gap, layout_style="vertical", - finger_radius=finger_radius, finger_axis="y", - ) - - sorted_normal = sorted(res_normal, key=lambda m: m.bounds[0][1]) - sorted_finger = sorted(res_finger, key=lambda m: m.bounds[0][1]) - - dist_normal = sorted_normal[1].bounds[0][1] - sorted_normal[0].bounds[1][1] - dist_finger = sorted_finger[1].bounds[0][1] - sorted_finger[0].bounds[1][1] - - assert dist_finger >= dist_normal + 2 * finger_radius - 0.01 - - - -class TestArrangeWithStableBounds: - """Tests fuer die von CLI und Web-App geteilte stabile Anordnung.""" - - def test_single_figure_bounds_and_copy(self, cube_mesh): - """XY wird um clearance + voxel_pitch gepaddet, Z nur um voxel_pitch/2. - - Der Z-Zuschlag gleicht die Inflation von _solidify_figure aus. Frueher - stand dort dasselbe Padding wie in XY, was die Bodenwand um bis zu - 2.5 mm zu dick machte. - """ - cfg = inlayer.Config(clearance=0.5, voxel_pitch=1.0, decimate_faces=1000) - arranged, (bmin, bmax), trans = inlayer.arrange_with_stable_bounds( - [cube_mesh], [cube_mesh], [cube_mesh], cfg - ) - pad = cfg.clearance + cfg.voxel_pitch - z_pad = cfg.voxel_pitch / 2 - np.testing.assert_allclose(bmin[:2], cube_mesh.bounds[0][:2] - pad) - np.testing.assert_allclose(bmax[:2], cube_mesh.bounds[1][:2] + pad) - np.testing.assert_allclose(bmin[2], cube_mesh.bounds[0][2] - z_pad) - np.testing.assert_allclose(bmax[2], cube_mesh.bounds[1][2] + z_pad) - # Einzelfigur wird nicht verschoben, aber wie im Multi-Pfad kopiert: - # der Aufrufer reicht gecachte Meshes herein. - assert arranged[0] is not cube_mesh - np.testing.assert_allclose(arranged[0].bounds, cube_mesh.bounds) - np.testing.assert_allclose(trans[0], [0.0, 0.0]) - - def test_multi_places_dilated_at_slot_centers(self, cube_mesh, sphere_mesh): - cfg = inlayer.Config(voxel_pitch=1.0, decimate_faces=1000) - meshes = [cube_mesh, sphere_mesh] - arranged, _, trans = inlayer.arrange_with_stable_bounds( - meshes, meshes, [m.copy() for m in meshes], cfg - ) - # Slot-Gitter muss dem direkten arrange_figures-Layout entsprechen - # (mit Dilations-Aufschlag, damit dilatierte Figuren den konfigurierten - # Abstand einhalten) - _, growth = inlayer._dilation_steps(cfg.clearance, cfg) - layout_gap = cfg.wall_thickness + 2.0 * growth - layout = inlayer.arrange_figures(meshes, layout_gap, cfg.layout_style) - for a, slot in zip(arranged, layout): - np.testing.assert_allclose( - a.bounds.mean(axis=0)[:2], slot.bounds.mean(axis=0)[:2], atol=1e-6 - ) - # Z bleibt unveraendert - for a, m in zip(arranged, meshes): - np.testing.assert_allclose(a.bounds[:, 2], m.bounds[:, 2], atol=1e-6) - - def test_finger_recesses_expand_bounds_in_x(self, cube_mesh): - cfg = inlayer.Config( - voxel_pitch=1.0, decimate_faces=1000, - enable_finger_recesses=True, finger_radius=6.0, - ) - _, (bmin, bmax), _ = inlayer.arrange_with_stable_bounds( - [cube_mesh], [cube_mesh], [cube_mesh], cfg - ) - pad = cfg.clearance + cfg.voxel_pitch - np.testing.assert_allclose(bmin[0], cube_mesh.bounds[0][0] - pad - 6.0) - np.testing.assert_allclose(bmax[0], cube_mesh.bounds[1][0] + pad + 6.0) - - # clearance/voxel_pitch decken beide Fehlerrichtungen ab: (0.5, 1.0) ist der - # Normalfall, (0.1, 1.0) und (0.05, 2.0) liegen unter voxel_pitch/4 – dort ist - # der reale Dilations-Zuwachs groesser als clearance und ein Aufschlag von - # 2*clearance wuerde den Abstand nicht retten (0.05/2.0 kollidierte sogar). - @pytest.mark.parametrize("clearance,voxel_pitch", [(0.5, 1.0), (0.1, 1.0), (0.05, 2.0)]) - def test_dilated_figures_keep_configured_gap(self, cube_mesh, clearance, voxel_pitch): - """Nach der Dilation muss der konfigurierte Abstand real eingehalten werden.""" - cfg = inlayer.Config( - clearance=clearance, voxel_pitch=voxel_pitch, figure_gap=2.0, - wall_thickness=2.0, decimate_faces=1000, layout_style="horizontal", - ) - # Echt dilatieren statt Kopien durchzureichen: nur so misst der Test die - # Kollision und nicht bloss die Aufschlags-Formel der Implementierung. - dilated = inlayer.dilate(cube_mesh, cfg.clearance, cfg) - refs = [cube_mesh.copy(), cube_mesh.copy()] - arranged, _, _ = inlayer.arrange_with_stable_bounds( - refs, refs, [dilated.copy(), dilated.copy()], cfg - ) - left, right = sorted(arranged, key=lambda m: m.bounds[0][0]) - assert cfg.figure_gap is not None # oben gesetzt; engt den Typ ein - assert right.bounds[0][0] - left.bounds[1][0] >= cfg.figure_gap - 1e-6 - - def test_manual_box_width_is_not_exceeded(self, cube_mesh): - """Bei manueller Box-Breite muss das Layout samt Rand hineinpassen. - - Der Packer reserviert je Seite Wandstaerke + Padding; rechnet er nur mit - dem Gap, passen zu viele Figuren in eine Reihe und die Box laeuft ueber - (dieselbe Bedingung, unter der build_inlay warnt). - """ - cfg = inlayer.Config( - clearance=1.0, voxel_pitch=1.0, figure_gap=2.0, box_width=70.0, - wall_thickness=2.0, decimate_faces=1000, layout_style="compact", - ) - meshes = [cube_mesh.copy() for _ in range(5)] - _, (bmin, bmax), _ = inlayer.arrange_with_stable_bounds( - meshes, meshes, [m.copy() for m in meshes], cfg - ) - assert (bmax[0] - bmin[0]) + 2 * cfg.wall_thickness <= cfg.box_width - - def test_dilation_growth_matches_reality(self, cube_mesh): - """_dilation_steps sagt den realen Bounding-Box-Zuwachs von dilate voraus.""" - cfg = inlayer.Config(clearance=0.4, voxel_pitch=0.4, decimate_faces=1000) - _, growth = inlayer._dilation_steps(cfg.clearance, cfg) - dilated = inlayer.dilate(cube_mesh, cfg.clearance, cfg) - measured = (dilated.extents - cube_mesh.extents) / 2.0 - np.testing.assert_allclose(measured, growth, atol=1e-6) - - -class TestStableBoundsFollowRotation: - """Regression: die Box muss die *reale* Figur umschliessen, nicht die Referenz. - - Die Web-App uebergibt als Referenz die unrotierten Figuren, damit die Slots - beim Drehen nicht springen. Frueher stammten auch die Box-Masse aus dieser - Referenz: eine um 90 Grad gedrehte Figur bekam eine Box nach ihrer - ungedrehten Ausdehnung, ragte seitlich heraus und schwebte weit ueber dem - Boden. Stabil sind die Slots, nicht die Box. - """ - - def _rotated_setup(self, cfg, rot_x): - base = trimesh.creation.box(extents=[10.0, 10.0, 30.0]) - rotated = inlayer.apply_euler_rotation(base, rot_x, 0.0, 0.0) - dilated = inlayer.dilate(rotated, cfg.clearance, cfg) - return base, rotated, dilated - - def test_bounds_enclose_rotated_figure(self): - """Die zurueckgegebenen Bounds umschliessen die gedrehte Figur in XY.""" - cfg = inlayer.Config(clearance=0.4, voxel_pitch=1.0, wall_thickness=2.0, - decimate_faces=1000) - base, rotated, dilated = self._rotated_setup(cfg, 90.0) - arranged, (bmin, bmax), _ = inlayer.arrange_with_stable_bounds( - [base], [rotated], [dilated], cfg - ) - # Nach 90 Grad um X ist die Figur in Y so hoch wie vorher in Z. - assert arranged[0].extents[1] > base.extents[1] * 2 - for axis in (0, 1, 2): - assert bmin[axis] <= arranged[0].bounds[0][axis] + 1e-6 - assert bmax[axis] >= arranged[0].bounds[1][axis] - 1e-6 - - def test_box_encloses_rotated_figure(self): - """build_inlay erzeugt eine Box, die die gedrehte Figur wirklich fasst.""" - cfg = inlayer.Config(clearance=0.4, voxel_pitch=1.0, wall_thickness=2.0, - decimate_faces=1000) - base, rotated, dilated = self._rotated_setup(cfg, 90.0) - arranged, bounds, _ = inlayer.arrange_with_stable_bounds( - [base], [rotated], [dilated], cfg - ) - inlay, w, d, h = inlayer.build_inlay( - arranged, cfg, stable_global_bounds=bounds - ) - fig_w, fig_d = arranged[0].extents[0], arranged[0].extents[1] - assert w >= fig_w + 2 * cfg.wall_thickness - 0.1 - assert d >= fig_d + 2 * cfg.wall_thickness - 0.1 - # Keine Figur darf die Mindestwandstaerke verletzen. - assert inlay.metadata["violating_indices"] == [] - - def test_box_height_follows_rotated_height(self): - """Die Box-Hoehe richtet sich nach der gedrehten, nicht der Referenz-Hoehe.""" - cfg = inlayer.Config(clearance=0.4, voxel_pitch=1.0, wall_thickness=2.0, - depth_fraction=0.7, decimate_faces=1000) - heights = {} - for rot_x in (0.0, 90.0): - base, rotated, dilated = self._rotated_setup(cfg, rot_x) - arranged, bounds, _ = inlayer.arrange_with_stable_bounds( - [base], [rotated], [dilated], cfg - ) - _, _, _, h = inlayer.build_inlay( - arranged, cfg, stable_global_bounds=bounds - ) - heights[rot_x] = h - # Liegend (90 Grad) ist die Figur deutlich flacher als stehend. - assert heights[90.0] < heights[0.0] - 5.0 - - def test_slots_stay_stable_while_rotating(self, cube_mesh): - """Die Slot-Translationen bleiben trotz Rotation unveraendert. - - Gegenprobe zum Fix: die Box folgt der Rotation, das Slot-Gitter nicht. - """ - cfg = inlayer.Config(clearance=0.4, voxel_pitch=1.0, figure_gap=2.0, - wall_thickness=2.0, decimate_faces=1000) - refs = [cube_mesh.copy(), cube_mesh.copy()] - translations = [] - for rot_z in (0.0, 45.0): - rotated = [inlayer.apply_euler_rotation(m, 0.0, 0.0, rot_z) for m in refs] - _, _, trans = inlayer.arrange_with_stable_bounds( - refs, rotated, [m.copy() for m in rotated], cfg - ) - translations.append(np.array(trans)) - np.testing.assert_allclose(translations[0], translations[1], atol=1e-6) diff --git a/tests/test_arrange_footprints.py b/tests/test_arrange_footprints.py new file mode 100644 index 0000000..6973ea7 --- /dev/null +++ b/tests/test_arrange_footprints.py @@ -0,0 +1,111 @@ +"""Tests for inlayer.arrange_footprints (the XY layout of several figures). + +The layout works on footprints - the XY extent of everything cut for a +figure - and returns the min corner of each. Every test here uses footprints +that force the case it claims to check: an earlier version compared figures +that the packer had put into different rows, so the X-gap and ordering +asserts never ran. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +import inlayer + + +def _rects(sizes, positions): + sizes = np.asarray(sizes, dtype=float) + return [(p, p + s) for p, s in zip(np.asarray(positions), sizes)] + + +def _separation(a, b) -> float: + """Distance between two rectangles along the axis that separates them.""" + return float(np.maximum(b[0] - a[1], a[0] - b[1]).max()) + + +def _assert_all_apart(sizes, positions, gap): + rects = _rects(sizes, positions) + for i in range(len(rects)): + for j in range(i + 1, len(rects)): + assert _separation(rects[i], rects[j]) >= gap - 1e-9, (i, j, rects[i], rects[j]) + + +class TestBasics: + def test_single_footprint_stays_at_the_origin(self): + np.testing.assert_allclose(inlayer.arrange_footprints([[10.0, 5.0]], 2.0), [[0.0, 0.0]]) + + def test_empty_list_raises(self): + with pytest.raises(ValueError, match="At least one mesh"): + inlayer.arrange_footprints(np.zeros((0, 2)), 2.0) + + @pytest.mark.parametrize("style", ["compact", "horizontal", "vertical"]) + def test_every_pair_keeps_the_gap(self, style): + sizes = [[10.0, 10.0], [8.0, 12.0], [15.0, 4.0], [3.0, 3.0]] + positions = inlayer.arrange_footprints(sizes, 3.0, style) + _assert_all_apart(sizes, positions, 3.0) + + +class TestCompact: + def test_same_row_is_exactly_gap_apart_in_x(self): + """Two small footprints share a row: the X gap is the configured one.""" + sizes = [[10.0, 10.0], [10.0, 10.0]] + positions = inlayer.arrange_footprints(sizes, 3.0, "compact", box_width=100.0) + assert positions[0][1] == positions[1][1] # really in one row + assert abs(positions[1][0] - positions[0][0]) == pytest.approx(13.0) + + def test_rows_are_gap_apart_in_y(self): + """A box width that fits one footprint per row forces a second row.""" + sizes = [[10.0, 10.0], [10.0, 6.0]] + positions = inlayer.arrange_footprints(sizes, 3.0, "compact", box_width=12.0) + assert positions[0][0] == positions[1][0] == 0.0 # really two rows + # The second row starts one row height plus the gap further up + assert positions[1][1] == pytest.approx(13.0) + + def test_largest_first(self): + sizes = [[3.0, 3.0], [10.0, 10.0], [5.0, 5.0]] + positions = inlayer.arrange_footprints(sizes, 2.0, "compact", box_width=100.0) + assert positions[1][0] == 0.0 + assert positions[2][0] < positions[0][0] + + def test_sort_keys_override_the_footprint_area(self): + """With the unrotated figures as keys the order survives a rotation.""" + sizes = [[3.0, 3.0], [10.0, 10.0]] + positions = inlayer.arrange_footprints( + sizes, 2.0, "compact", sort_keys=[200.0, 1.0], box_width=100.0 + ) + assert positions[0][0] < positions[1][0] + + def test_box_width_limits_the_rows(self): + """Rows are packed with the full footprints (review B14). + + Packing with the bare figure widths and adding the recesses afterwards + let a row of k figures grow 2 * (k - 1) * finger_radius past the box. + """ + sizes = [[22.0, 12.0]] * 5 + positions = inlayer.arrange_footprints(sizes, 2.0, "compact", box_width=70.0, margin=2.0) + right = (positions[:, 0] + 22.0).max() + assert right <= 70.0 - 2 * 2.0 + 1e-9 + _assert_all_apart(sizes, positions, 2.0) + + def test_auto_width_is_roughly_square(self): + sizes = [[10.0, 10.0]] * 9 + positions = inlayer.arrange_footprints(sizes, 2.0, "compact") + span = (positions + 10.0).max(axis=0) + assert 0.5 < span[0] / span[1] < 2.0 + + +class TestHorizontalAndVertical: + def test_horizontal_smallest_first_bottoms_flush(self): + sizes = [[10.0, 10.0], [8.0, 8.0]] + positions = inlayer.arrange_footprints(sizes, 5.0, "horizontal") + np.testing.assert_allclose(positions[:, 1], 0.0) + assert positions[1][0] == 0.0 # the smaller one first + assert positions[0][0] == pytest.approx(13.0) + + def test_vertical_keeps_order_and_centres_in_x(self): + sizes = [[10.0, 10.0], [4.0, 6.0]] + positions = inlayer.arrange_footprints(sizes, 5.0, "vertical") + np.testing.assert_allclose(positions[:, 0] + np.asarray(sizes)[:, 0] / 2, 0.0) + assert positions[1][1] == pytest.approx(15.0) diff --git a/tests/test_build_inlay.py b/tests/test_build_inlay.py index bbf5a5f..1656c9c 100644 --- a/tests/test_build_inlay.py +++ b/tests/test_build_inlay.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import inspect import numpy as np @@ -10,6 +11,7 @@ import inlayer from inlayer import Config +from tests import geometry_probe as gp class TestBuildInlayBasic: @@ -32,24 +34,29 @@ def test_returned_dimensions_are_floats(self, dilated_cube, fast_test_config): class TestBuildInlayAutoDimensions: - def test_auto_xy_includes_wall_thickness(self, dilated_cube, fast_test_config): - # Auto-XY = Figur-XY + 2 * wall_thickness - fig_size = dilated_cube.extents - _, w, d, _ = inlayer.build_inlay(dilated_cube, fast_test_config) - expected_w = fig_size[0] + 2 * fast_test_config.wall_thickness - expected_d = fig_size[1] + 2 * fast_test_config.wall_thickness - assert w == pytest.approx(expected_w, abs=1e-6) - assert d == pytest.approx(expected_d, abs=1e-6) - - def test_auto_height_uses_depth_fraction(self, dilated_cube, fast_test_config): - # Auto-H = wall_thickness + depth_fraction * (fig_z + voxel_pitch). - # Der voxel_pitch-Aufschlag gleicht die Inflation aus, die - # _solidify_figure beim Marching Cubes auftraegt – ohne ihn faellt die - # Bodenwand um voxel_pitch/2 duenner aus als konfiguriert. - fig_z = dilated_cube.extents[2] + fast_test_config.voxel_pitch - _, _, _, h = inlayer.build_inlay(dilated_cube, fast_test_config) - expected = fast_test_config.wall_thickness + fast_test_config.depth_fraction * fig_z - assert h == pytest.approx(expected, abs=1e-6) + """The box is measured around the real cavity, not predicted from the figure. + + The old formulas (figure + 2 * wall, wall + depth_fraction * (height + + pitch)) were exactly what these tests asserted - and the walls came out + 1.75 mm or 2.5 mm instead of 2.0, because voxelization shifts a cavity by + up to half a pitch depending on where it lies on the grid. + """ + + def test_auto_box_leaves_exactly_the_wall_around_the_cavity(self, dilated_cube, fast_test_config): + inlay, w, d, h = inlayer.build_inlay(dilated_cube, fast_test_config) + wall = fast_test_config.wall_thickness + assert w >= dilated_cube.extents[0] + 2 * wall + assert d >= dilated_cube.extents[1] + 2 * wall + walls = gp.outer_walls(inlay, w, d, h) + assert walls["side"] == pytest.approx(wall, abs=inlayer.WALL_TOLERANCE_MM) + assert walls["floor"] == pytest.approx(wall, abs=inlayer.WALL_TOLERANCE_MM) + + def test_auto_height_sinks_depth_fraction_of_the_figure(self, dilated_cube, fast_test_config): + inlay, w, d, h = inlayer.build_inlay(dilated_cube, fast_test_config) + x, y, _ = dilated_cube.bounds.mean(axis=0) + inlay.metadata["placements"][0] + depth = h - gp.pocket_floor(inlay, x, y, h) + expected = fast_test_config.depth_fraction * dilated_cube.extents[2] + assert expected <= depth <= expected + fast_test_config.voxel_pitch class TestBuildInlayManualOverrides: @@ -68,24 +75,14 @@ def test_manual_width_used(self, dilated_cube): assert h == pytest.approx(fig_size[2] + 5.0, abs=1e-6) def test_partial_override_keeps_auto(self, dilated_cube, fast_test_config): - # Nur box_width manuell setzen; box_depth/box_height sollen automatisch sein. - fig_size = dilated_cube.extents - manual_w = fig_size[0] + 20.0 - cfg = Config( - wall_thickness=fast_test_config.wall_thickness, - depth_fraction=fast_test_config.depth_fraction, - voxel_pitch=fast_test_config.voxel_pitch, - box_width=manual_w, - ) + # Only box_width is manual; box_depth/box_height stay automatic. + manual_w = dilated_cube.extents[0] + 20.0 + _, _, auto_d, auto_h = inlayer.build_inlay(dilated_cube, fast_test_config) + cfg = dataclasses.replace(fast_test_config, box_width=manual_w) _, w, d, h = inlayer.build_inlay(dilated_cube, cfg) assert w == pytest.approx(manual_w, abs=1e-6) - # d/h folgen weiterhin der Auto-Berechnung - assert d == pytest.approx(fig_size[1] + 2 * cfg.wall_thickness, abs=1e-6) - assert h == pytest.approx( - cfg.wall_thickness - + cfg.depth_fraction * (fig_size[2] + cfg.voxel_pitch), - abs=1e-6, - ) + assert d == pytest.approx(auto_d, abs=1e-6) + assert h == pytest.approx(auto_h, abs=1e-6) def test_undersized_box_emits_warning(self, dilated_cube, fast_test_config, capsys): # Eine viel zu kleine Box muss eine WARN-Zeile auf stdout produzieren @@ -119,23 +116,23 @@ def test_empty_mesh_raises(self, fast_test_config): class TestBuildInlayOffsets: - def test_offset_changes_inlay_bounds(self, dilated_cube, fast_test_config): - # Mit einem Offset, der die Figur aus der Box schiebt, muss das Ergebnis - # eine andere (groessere/kleinere) Aussparung aufweisen. - cfg_zero = fast_test_config - cfg_off = Config( - clearance=fast_test_config.clearance, - wall_thickness=fast_test_config.wall_thickness, - depth_fraction=fast_test_config.depth_fraction, - voxel_pitch=fast_test_config.voxel_pitch, - decimate_faces=fast_test_config.decimate_faces, - offset_z=2.0, + def test_offset_moves_the_cavity_inside_a_fixed_box(self, dilated_cube, fast_test_config): + """The offset moves the cavity by exactly that much; the box stays. + + The previous version only asserted that both inlays had faces, so a + pipeline that ignored the offsets passed it (review N4). + """ + plain = inlayer.build_inlay(dilated_cube, fast_test_config) + moved = inlayer.build_inlay( + dilated_cube, dataclasses.replace(fast_test_config, offset_x=1.0, offset_z=-1.0) ) - inlay_zero, *_ = inlayer.build_inlay(dilated_cube, cfg_zero) - inlay_off, *_ = inlayer.build_inlay(dilated_cube, cfg_off) - # Beide muessen valide Meshes sein; das Volumen darf sich aber unterscheiden. - assert len(inlay_zero.faces) > 0 - assert len(inlay_off.faces) > 0 + assert moved[1:] == pytest.approx(plain[1:], abs=1e-6) + (before,) = gp.cavities(*plain) + (after,) = gp.cavities(*moved) + shift = np.array(after.bounding_box()) - np.array(before.bounding_box()) + # x: whole pocket moves; z: the floor moves, the open top stays clipped + np.testing.assert_allclose(shift[[0, 3]], 1.0, atol=1e-3) + assert shift[2] == pytest.approx(-1.0, abs=1e-3) class TestBuildInlaySignature: @@ -150,6 +147,16 @@ def test_no_individual_rotations_parameter(self): params = inspect.signature(inlayer.build_inlay).parameters assert "individual_rotations" not in params + def test_no_stable_global_bounds_parameter(self): + """build_inlay dimensions the box itself, from the real cavities. + + Box sizing used to be split between the caller (stable bounds) and + build_inlay; the documented call without them got neither the XY + compensation nor room for the finger recesses. + """ + params = inspect.signature(inlayer.build_inlay).parameters + assert "stable_global_bounds" not in params + def test_rejects_individual_rotations_keyword(self, dilated_cube, fast_test_config): # Ein Aufrufer, der den alten Parameter uebergibt, soll scheitern statt # stillschweigend eine wirkungslose Rotation zu "akzeptieren". @@ -165,15 +172,11 @@ class TestBuildInlayMultiMesh: """Tests fuer Multi-Mesh-Eingabe (Liste von Figuren).""" def test_multi_mesh_returns_valid_inlay(self, dilated_cube, dilated_sphere, fast_test_config): - """Zwei Meshes als Liste ergeben ein gueltiges Inlay.""" - # Meshes nebeneinander platzieren, damit sie nicht ueberlappen - arranged = inlayer.arrange_figures( - [dilated_cube, dilated_sphere], gap=fast_test_config.wall_thickness - ) - inlay, w, d, h = inlayer.build_inlay(arranged, fast_test_config) + """Two meshes (unarranged - build_inlay lays them out) give two pockets.""" + inlay, w, d, h = inlayer.build_inlay([dilated_cube, dilated_sphere], fast_test_config) assert isinstance(inlay, trimesh.Trimesh) - assert len(inlay.faces) > 0 - assert w > 0 and d > 0 and h > 0 + assert len(gp.cavities(inlay, w, d, h)) == 2 + assert inlay.metadata["wall_check"]["passes_min_wall"] is True def test_single_mesh_list_same_as_single(self, dilated_cube, fast_test_config): """[mesh] als Liste muss dasselbe Ergebnis wie mesh allein liefern.""" @@ -185,21 +188,16 @@ def test_single_mesh_list_same_as_single(self, dilated_cube, fast_test_config): # Face-Count kann leicht abweichen (Kopie vs. Original), aber Groessenordnung gleich assert abs(len(inlay_single.faces) - len(inlay_list.faces)) < 100 - def test_multi_mesh_box_encompasses_all(self, dilated_cube, dilated_sphere, fast_test_config): - """Box muss gross genug fuer alle Figuren sein.""" - arranged = inlayer.arrange_figures( - [dilated_cube, dilated_sphere], gap=fast_test_config.wall_thickness - ) - _, w, d, h = inlayer.build_inlay(arranged, fast_test_config) - - # Kombinierte XY-Ausdehnung berechnen - import numpy as np - all_bounds = np.array([m.bounds for m in arranged]) - combined_size = all_bounds[:, 1, :].max(axis=0) - all_bounds[:, 0, :].min(axis=0) - min_w = combined_size[0] + 2 * fast_test_config.wall_thickness - min_d = combined_size[1] + 2 * fast_test_config.wall_thickness - assert w >= min_w - 0.5, f"Box-Breite {w:.1f} < Mindest {min_w:.1f}" - assert d >= min_d - 0.5, f"Box-Tiefe {d:.1f} < Mindest {min_d:.1f}" + def test_placements_put_every_figure_inside_the_box(self, dilated_cube, dilated_sphere, fast_test_config): + """`placements` is what the preview draws with; it must match the cut.""" + figs = [dilated_cube, dilated_sphere] + inlay, w, d, h = inlayer.build_inlay(figs, fast_test_config) + for fig, placement in zip(figs, inlay.metadata["placements"]): + lo, hi = fig.bounds + placement + wall = fast_test_config.wall_thickness + assert lo[0] >= wall and lo[1] >= wall and hi[0] <= w - wall and hi[1] <= d - wall + assert lo[2] >= wall + assert hi[2] > h # stands out of the box by (1 - depth_fraction) def test_build_inlay_individual_offsets(self, dilated_cube, dilated_sphere, fast_test_config): """Prueft, ob individuelle Offsets pro Figur korrekt angewendet werden.""" @@ -221,21 +219,13 @@ def test_invalid_box_shape_raises(self): with pytest.raises(ValueError): Config(box_shape="hexagon") - def test_auto_diameter_is_enclosing_circle(self, dilated_cube, fast_test_config): - # Auto-Durchmesser = Umkreis der Figuren-XY-Bounds + 2 * wall_thickness - cfg = Config( - wall_thickness=fast_test_config.wall_thickness, - depth_fraction=fast_test_config.depth_fraction, - voxel_pitch=fast_test_config.voxel_pitch, - box_shape="cylinder", - ) - fig_size = dilated_cube.extents + def test_auto_diameter_encloses_the_cavity_with_the_wall(self, dilated_cube, fast_test_config): + # Circumcircle of the cavity's footprint plus 2 * wall_thickness + cfg = dataclasses.replace(fast_test_config, box_shape="cylinder") inlay, w, d, h = inlayer.build_inlay(dilated_cube, cfg) - expected = float(np.hypot(fig_size[0], fig_size[1])) + 2 * cfg.wall_thickness - assert w == pytest.approx(expected, abs=1e-6) - assert d == pytest.approx(expected, abs=1e-6) - assert isinstance(inlay, trimesh.Trimesh) - assert len(inlay.faces) > 0 + assert w == d + assert w >= float(np.hypot(*dilated_cube.extents[:2])) + 2 * cfg.wall_thickness + assert gp.cylinder_side_wall(inlay) >= cfg.wall_thickness - inlayer.WALL_TOLERANCE_MM def test_inlay_bounds_match_diameter(self, dilated_cube, fast_test_config): # Die Bounding-Box des Zylinder-Inlays entspricht Durchmesser x Durchmesser x Hoehe @@ -304,23 +294,11 @@ def test_off_center_figure_flagged_as_violating(self, dilated_cube, fast_test_co assert 0 in inlay.metadata["violating_indices"] def test_multi_mesh_cylinder(self, dilated_cube, dilated_sphere, fast_test_config): - arranged = inlayer.arrange_figures( - [dilated_cube, dilated_sphere], gap=fast_test_config.wall_thickness - ) - cfg = Config( - wall_thickness=fast_test_config.wall_thickness, - depth_fraction=fast_test_config.depth_fraction, - voxel_pitch=fast_test_config.voxel_pitch, - box_shape="cylinder", - ) - inlay, w, d, h = inlayer.build_inlay(arranged, cfg) - assert len(inlay.faces) > 0 + cfg = dataclasses.replace(fast_test_config, box_shape="cylinder") + inlay, w, d, h = inlayer.build_inlay([dilated_cube, dilated_sphere], cfg) assert w == d - # Umkreis muss die kombinierte XY-Ausdehnung umschliessen - all_bounds = np.array([m.bounds for m in arranged]) - combined = all_bounds[:, 1, :].max(axis=0) - all_bounds[:, 0, :].min(axis=0) - min_diameter = float(np.hypot(combined[0], combined[1])) + 2 * cfg.wall_thickness - assert w >= min_diameter - 0.5 + assert gp.cylinder_side_wall(inlay) >= cfg.wall_thickness - inlayer.WALL_TOLERANCE_MM + assert inlay.metadata["wall_check"]["passes_min_wall"] is True class TestBuildInlayFingerRecesses: @@ -342,54 +320,55 @@ def test_finger_recesses_in_metadata(self, dilated_cube): assert ext[0] == pytest.approx(3.0, abs=0.1) assert ext[1] == pytest.approx(3.0, abs=0.1) - def test_finger_recesses_subtracts_volume(self, dilated_cube): - """Prueft, ob Fingermulden das Volumen des Inlays reduzieren (CSG Subtraktion).""" - cfg_no = Config( - voxel_pitch=1.0, - enable_finger_recesses=False, - wall_thickness=4.0, - ) - cfg_yes = Config( - voxel_pitch=1.0, - enable_finger_recesses=True, - finger_radius=1.5, - wall_thickness=4.0, - ) - inlay_no, *_ = inlayer.build_inlay(dilated_cube, cfg_no) - inlay_yes, *_ = inlayer.build_inlay(dilated_cube, cfg_yes) - # Mit Fingermulden muss das Volumen geringer sein, da Material subtrahiert wurde - assert inlay_yes.volume < inlay_no.volume + def test_finger_recesses_remove_material(self, dilated_cube): + """The recesses are cut: more is removed from the box than without them.""" + base = dict(voxel_pitch=1.0, wall_thickness=4.0) + removed = [] + for enabled in (False, True): + inlay, w, d, h = inlayer.build_inlay( + dilated_cube, Config(**base, enable_finger_recesses=enabled, finger_radius=1.5) + ) + removed.append(w * d * h - inlay.volume) + assert removed[1] > removed[0] - def test_finger_recesses_flush_with_top(self, dilated_cube): - """Prueft, ob die Fingermulden-Halbkugeln in Z-Richtung buendig mit der Oberkante des Inlays abschliessen (Z-Max bei h, Z-Min bei h - r).""" + def test_recess_reaches_through_the_top_face(self, dilated_cube): + """Hemisphere r below the top face, shaft up through it (never a roof).""" r = 1.5 - cfg = Config( - voxel_pitch=1.0, - enable_finger_recesses=True, - finger_radius=r, - wall_thickness=4.0, - ) + cfg = Config(voxel_pitch=1.0, enable_finger_recesses=True, finger_radius=r, wall_thickness=4.0) inlay, w, d, h = inlayer.build_inlay(dilated_cube, cfg) - recesses = inlay.metadata["finger_recesses"] - for hemi in recesses: - # Die flache Oberseite der Halbkugel liegt exakt bei box_h - assert hemi.bounds[1][2] == pytest.approx(h, abs=1e-3) - # Die Unterseite der Halbkugel liegt genau r Millimeter darunter - assert hemi.bounds[0][2] == pytest.approx(h - r, abs=1e-3) + for recess in inlay.metadata["finger_recesses"]: + assert recess.bounds[1][2] == pytest.approx(h + inlayer.CUT_OVERSHOOT_MM, abs=1e-3) + assert recess.bounds[0][2] == pytest.approx(h - r, abs=1e-3) + + def test_recess_template_is_a_closed_hemisphere_with_shaft(self): + cfg = Config(enable_finger_recesses=True, finger_radius=5.0, finger_recess_z_offset=3.0) + template = inlayer._recess_template(cfg) + shaft = cfg.finger_recess_z_offset + inlayer.CUT_OVERSHOOT_MM + assert template.is_volume + np.testing.assert_allclose(template.bounds, [[-5, -5, -5], [5, 5, shaft]], atol=1e-6) + expected = 2 / 3 * np.pi * 5**3 + np.pi * 5**2 * shaft + assert template.volume == pytest.approx(expected, rel=0.01) def test_search_band_scales_with_voxel_pitch(self): - """Das Suchband fuer die Muldenposition waechst mit dem voxel_pitch. - - Bei grobem Pitch liegen weniger Vertices nahe der Y-Mitte; ein fixes - Band wuerde die Position verrauschen. Untergrenze bleibt FINGER_BAND_MIN_MM. - """ - assert inlayer.FINGER_BAND_VOXELS > 0 - assert inlayer.FINGER_BAND_MIN_MM > 0 - fein = max(inlayer.FINGER_BAND_MIN_MM, inlayer.FINGER_BAND_VOXELS * 0.1) - grob = max(inlayer.FINGER_BAND_MIN_MM, inlayer.FINGER_BAND_VOXELS * 2.0) - # Feiner Pitch faellt auf die Untergrenze, grober Pitch skaliert darueber hinaus. - assert fein == inlayer.FINGER_BAND_MIN_MM - assert grob > fein + """At a coarse pitch fewer vertices lie near the grip position; a fixed + band would make the position noisy. The floor stays FINGER_BAND_MIN_MM.""" + assert inlayer._finger_band(0.1) == inlayer.FINGER_BAND_MIN_MM + assert inlayer._finger_band(2.0) == pytest.approx(inlayer.FINGER_BAND_VOXELS * 2.0) + assert inlayer._finger_band(2.0) > inlayer.FINGER_BAND_MIN_MM + + def test_build_inlay_uses_the_search_band(self, dilated_cube, monkeypatch): + """Not a re-implementation of the formula: build_inlay really calls it.""" + pitches = [] + original = inlayer._finger_band + + def spy(pitch): + pitches.append(pitch) + return original(pitch) + + monkeypatch.setattr(inlayer, "_finger_band", spy) + cfg = Config(voxel_pitch=1.0, enable_finger_recesses=True, finger_radius=1.5, wall_thickness=4.0) + inlayer.build_inlay(dilated_cube, cfg) + assert pitches == [1.0] def test_recesses_positioned_at_figure_edges(self, dilated_cube): """Die Mulden sitzen links und rechts der Figur, nicht an derselben Stelle.""" @@ -444,7 +423,8 @@ def test_recess_z_offset_lowers_recesses(self, dilated_cube): ) inlay, w, d, h = inlayer.build_inlay(dilated_cube, cfg) for hemi in inlay.metadata["finger_recesses"]: - assert hemi.bounds[1][2] == pytest.approx(h - offset, abs=1e-3) + # The shaft still reaches through the top face + assert hemi.bounds[1][2] == pytest.approx(h + inlayer.CUT_OVERSHOOT_MM, abs=1e-3) assert hemi.bounds[0][2] == pytest.approx(h - offset - r, abs=1e-3) def test_recess_axis_validation(self): @@ -493,7 +473,7 @@ def test_recess_position_slides_recesses_along_the_figure(self, dilated_cube): # Sliding along the figure must not sink the recesses (that is z_offset's job) assert h_shifted == pytest.approx(h, abs=1e-6) for hemi in inlay_shifted.metadata["finger_recesses"]: - assert hemi.bounds[1][2] == pytest.approx(h_shifted, abs=1e-3) + assert hemi.bounds[0][2] == pytest.approx(h_shifted - r, abs=1e-3) def test_recess_position_is_symmetric_around_the_centre(self, dilated_cube): """-p and +p mirror each other around the centred position.""" @@ -608,10 +588,9 @@ def _by_figure(inlay, cross_axis=1): def test_each_figure_gets_its_own_position(self, dilated_cube, dilated_sphere): """Two figures, two different grip points in one inlay.""" figs = [dilated_cube, dilated_sphere] - arranged = inlayer.arrange_figures(figs, gap=4.0) - centred, *_ = inlayer.build_inlay(arranged, Config(**self.CFG)) + centred, *_ = inlayer.build_inlay(figs, Config(**self.CFG)) mixed, *_ = inlayer.build_inlay( - arranged, Config(**self.CFG), individual_recess_positions=[1.0, 0.0] + figs, Config(**self.CFG), individual_recess_positions=[1.0, 0.0] ) centred_by_fig = self._by_figure(centred) diff --git a/tests/test_config.py b/tests/test_config.py index 3fbc150..7b1f1ba 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -2,6 +2,9 @@ from __future__ import annotations +import math +from dataclasses import fields + import pytest from inlayer import Config @@ -132,3 +135,45 @@ def test_box_dimensions_positive_allowed(self): assert c.box_width == 50.0 assert c.box_depth == 40.0 assert c.box_height == 20.0 + + +FLOAT_FIELDS = [f.name for f in fields(Config) if f.type in (float, float | None)] + + +class TestConfigNonFinite: + """NaN and inf passed every `x < 0` check and failed later with unrelated + errors ("CSG difference failed", "cannot convert float NaN to integer").""" + + def test_every_float_field_is_covered(self): + assert {"clearance", "wall_thickness", "box_diameter", "offset_z"} <= set(FLOAT_FIELDS) + + @pytest.mark.parametrize("name", FLOAT_FIELDS) + @pytest.mark.parametrize("value", [math.nan, math.inf, -math.inf]) + def test_rejected_with_the_field_name(self, name, value): + with pytest.raises(ValueError, match=f"{name} must be a finite number"): + Config(**{name: value}) + + +class TestConfigMessages: + """Each range has its own message; they used to share "must be > 0".""" + + def test_zero_allowed_fields_say_so(self): + with pytest.raises(ValueError, match=r"clearance must be >= 0"): + Config(clearance=-0.5) + with pytest.raises(ValueError, match=r"finger_recess_z_offset must be >= 0"): + Config(finger_recess_z_offset=-1.0) + + def test_depth_fraction_names_both_bounds(self): + with pytest.raises(ValueError, match=r"depth_fraction must be > 0 and <= 1 \(is 1.5\)"): + Config(depth_fraction=1.5) + + def test_decimate_faces_names_its_minimum(self): + with pytest.raises(ValueError, match=r"decimate_faces must be >= 4 \(is 3\)"): + Config(decimate_faces=3) + + def test_zero_is_allowed_where_the_message_says_so(self): + Config(clearance=0.0, finger_recess_z_offset=0.0) + + def test_effective_figure_gap(self): + assert Config(wall_thickness=3.0).effective_figure_gap == 3.0 + assert Config(wall_thickness=3.0, figure_gap=1.5).effective_figure_gap == 1.5 diff --git a/tests/test_dilate.py b/tests/test_dilate.py index 38051a6..e8827f1 100644 --- a/tests/test_dilate.py +++ b/tests/test_dilate.py @@ -66,6 +66,47 @@ def test_uses_voxel_pitch_from_config(self, prepared_cube): assert isinstance(m, trimesh.Trimesh) assert len(m.faces) > 0 +class TestIsotropicClearance: + """Slopes get the same clearance as axis-parallel faces (review B27). + + scipy's default structuring element grows an octahedron: with 2 mm of + clearance a sphere got 2.11 mm along the axes but 1.50 mm along the space + diagonals - the figure jammed on slopes. + """ + + DIRECTIONS = np.array( + [d for d in np.ndindex(3, 3, 3) if d != (1, 1, 1)], dtype=float + ) - 1.0 # the 26 axis, face-diagonal and space-diagonal directions + + @staticmethod + def _radius(mesh, direction) -> float: + from tests.geometry_probe import to_manifold + + d = direction / np.linalg.norm(direction) + return float(np.linalg.norm(to_manifold(mesh).ray_cast((0.0, 0.0, 0.0), tuple(d * 50.0))[0].position)) + + @pytest.mark.parametrize("clearance,pitch", [(2.0, 0.4), (1.0, 0.5)]) + def test_dilation_grows_the_same_in_every_direction(self, tmp_path, clearance, pitch): + """What dilate adds, per direction, measured by ray from the centre. + + Compared with the prepared figure rather than the analytic sphere: + voxelizing the input already puts the surface 0.20-0.32 mm out + depending on the direction (at pitch 0.4) - discretization, not + dilate's doing. + """ + cfg = Config(clearance=clearance, voxel_pitch=pitch, decimate_faces=5000) + path = tmp_path / "sphere.stl" + trimesh.creation.icosphere(subdivisions=4, radius=10.0).export(file_obj=str(path)) + prepared = inlayer.prepare_figure(str(path), cfg) + dilated = inlayer.dilate(prepared, cfg.clearance, cfg) + growth = np.array([ + self._radius(dilated, d) - self._radius(prepared, d) for d in self.DIRECTIONS + ]) + # The cross-only dilation grew 1.9 mm along the axes, ~1.1 mm along + # the space diagonals + assert np.ptp(growth) <= pitch / 4, growth.round(3) + + @pytest.mark.slow class TestEffectiveClearance: """Regressionstest fuer die Inflations-Kompensation in dilate. diff --git a/tests/test_geometry_invariants.py b/tests/test_geometry_invariants.py new file mode 100644 index 0000000..2d3afd8 --- /dev/null +++ b/tests/test_geometry_invariants.py @@ -0,0 +1,256 @@ +"""Geometry invariants, measured on the finished inlay mesh. + +Every other test checks a formula, a bounding box or a metadata field - and +the whole suite stayed green while the printed part was wrong: floors 25 % +too thick, walls between cavities one voxel too thin, short figures without a +pocket, recesses breaking through the floor, sealed voids. These tests measure +the output with `geometry_probe` (manifold3d booleans, ray casts, min_gap), +which knows nothing about how the pipeline got there. The review scenario each +one reproduces is named in its docstring (appendix B of the review plan). +""" + +from __future__ import annotations + +import numpy as np +import pytest +import trimesh + +from tests import geometry_probe as gp +import inlayer +from inlayer import Config + +TOL = inlayer.WALL_TOLERANCE_MM + + +def _box(x, y, z, at=(0.0, 0.0, 0.0)) -> trimesh.Trimesh: + """Cuboid standing on z = at[2] (STLs rarely sit centred on the origin).""" + m = trimesh.creation.box(extents=[x, y, z]) + m.apply_translation(np.asarray(at) + [0.0, 0.0, z / 2]) + return m + + +SHAPES = { + "cube": lambda: _box(10.0, 10.0, 10.0), + "sphere": lambda: trimesh.creation.icosphere(subdivisions=3, radius=5.0), + "cylinder": lambda: trimesh.creation.cylinder(radius=4.0, height=12.0, sections=32), +} +PITCHES = [0.5, 1.0, pytest.param(0.4, marks=pytest.mark.slow)] + + +_DILATED: dict = {} + + +def _dilate(mesh: trimesh.Trimesh, cfg: Config) -> trimesh.Trimesh: + """dilate, shared between tests: it dominates their runtime, and + build_inlay copies its input, so reusing a result is safe.""" + key = (mesh.vertices.tobytes(), mesh.faces.tobytes(), cfg.clearance, cfg.voxel_pitch) + if key not in _DILATED: + _DILATED[key] = inlayer.dilate(mesh, cfg.clearance, cfg) + return _DILATED[key] + + +def _build(meshes, cfg, **kwargs): + """dilate + build_inlay, as both entry points do.""" + dilated = [_dilate(m, cfg) for m in meshes] + inlay, w, d, h = inlayer.build_inlay(dilated, cfg, **kwargs) + return inlay, w, d, h, dilated + + +def _cfg(**overrides) -> Config: + return Config(**{"voxel_pitch": 0.5, "decimate_faces": 1000, **overrides}) + + +class TestOuterWalls: + @pytest.mark.parametrize("pitch", PITCHES) + @pytest.mark.parametrize("shape", sorted(SHAPES)) + def test_side_and_floor_walls_are_the_wall_thickness(self, shape, pitch): + """Not thicker, not thinner: the floor used to be wall + pitch/2 + (review N10), the side walls 1.75-2.4 mm depending on the path (R5).""" + cfg = _cfg(voxel_pitch=pitch) + inlay, w, d, h, _ = _build([SHAPES[shape]()], cfg) + walls = gp.outer_walls(inlay, w, d, h) + assert walls["side"] == pytest.approx(cfg.wall_thickness, abs=TOL) + assert walls["floor"] == pytest.approx(cfg.wall_thickness, abs=TOL) + check = inlay.metadata["wall_check"] + assert check["passes_min_wall"] is True + assert check["min_wall_mm"] == pytest.approx(min(walls.values()), abs=TOL) + + @pytest.mark.parametrize("pitch", PITCHES) + def test_cylinder_box_keeps_the_wall_at_the_corners(self, pitch): + cfg = _cfg(voxel_pitch=pitch, box_shape="cylinder") + inlay, *_ = _build([_box(10.0, 10.0, 10.0), _box(10.0, 10.0, 10.0)], cfg) + # The circle runs through the corners of the footprints' rectangle; + # marching cubes bevels the cutters' corners a little, so never thinner + # and at most about a voxel thicker. + side = gp.cylinder_side_wall(inlay) + assert cfg.wall_thickness - TOL <= side <= cfg.wall_thickness + pitch + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + +class TestInnerWalls: + @pytest.mark.parametrize("pitch", PITCHES) + @pytest.mark.parametrize( + "n,style", [(2, "compact"), (2, "horizontal"), (2, "vertical"), (3, "compact")] + ) + def test_wall_between_cavities_is_figure_gap(self, n, style, pitch): + """figure_gap is "the wall between two cavities" - it came out + figure_gap - voxel_pitch (1.6 / 1.0 mm instead of 2.0, review R12/B13).""" + cfg = _cfg(voxel_pitch=pitch, figure_gap=2.0, layout_style=style) + inlay, w, d, h, _ = _build([_box(10.0, 10.0, 10.0) for _ in range(n)], cfg) + assert len(gp.cavities(inlay, w, d, h)) == n + assert gp.inner_gap(inlay, w, d, h) == pytest.approx(2.0, abs=TOL) + + +class TestZPlacement: + @pytest.mark.parametrize("short", [8.0, 20.0]) + def test_every_figure_sinks_depth_fraction_of_its_own_height(self, short): + """A short figure next to a tall one got no pocket at all (8 mm, review + B3) or sank 43 % instead of 70 % (20 mm, B4): all were top-flush.""" + cfg = _cfg() + inlay, w, d, h, dilated = _build([_box(10.0, 10.0, 40.0), _box(10.0, 10.0, short)], cfg) + assert len(gp.cavities(inlay, w, d, h)) == 2 + for fig, placement in zip(dilated, inlay.metadata["placements"]): + x, y, _ = fig.bounds.mean(axis=0) + placement + depth = h - gp.pocket_floor(inlay, x, y, h) + expected = cfg.depth_fraction * fig.extents[2] + # plus up to one voxel the solidification adds below the figure + assert expected - TOL <= depth <= expected + cfg.voxel_pitch + TOL + + def test_z_origin_of_the_stl_does_not_matter(self): + """Cubes at z 0..10 and 30..40 became one solid block without any + cavity - and the CLI reported "Success" (review R1/B2).""" + cfg = _cfg() + apart = _build([_box(10, 10, 10), _box(10, 10, 10, at=(0, 0, 30))], cfg) + level = _build([_box(10, 10, 10), _box(10, 10, 10)], cfg) + inlay, w, d, h = apart[:4] + assert len(gp.cavities(inlay, w, d, h)) == 2 + assert (w, d, h) == pytest.approx(level[1:4], abs=1e-6) + + def test_translation_does_not_change_the_result(self): + cfg = _cfg() + here = _build([_box(12, 8, 10)], cfg) + there = _build([_box(12, 8, 10, at=(100, -50, 100))], cfg) + assert here[1:4] == pytest.approx(there[1:4], abs=TOL) + assert gp.outer_walls(*here[:4]) == pytest.approx(gp.outer_walls(*there[:4]), abs=TOL) + + def test_flipping_one_figure_keeps_the_box_height(self): + """rot_x = 180 on one of two identical figures raised the box from + 17 to 31 mm and the floor to 22 mm (review B1): rotation turns about + the origin and moved the figure down.""" + cfg = _cfg() + base = _box(10, 10, 20) + upright = _build([base, base.copy()], cfg) + flipped = _build([base, inlayer.apply_euler_rotation(base, 180, 0, 0)], cfg) + assert flipped[3] == pytest.approx(upright[3], abs=TOL) + + @pytest.mark.parametrize("offset_z", [0.0, -0.5]) + def test_cavity_never_seals_at_full_depth(self, offset_z): + """depth_fraction 1.0 with a lowered figure left the pocket closed at + the top - a void in the print, two shells in the STL (review R8/B9).""" + cfg = _cfg(voxel_pitch=0.4, depth_fraction=1.0) + inlay, w, d, h, dilated = _build( + [_box(10, 10, 10)], cfg, individual_offsets=[(0.0, 0.0, offset_z)] + ) + assert gp.shell_count(inlay) == 1 + x, y, _ = dilated[0].bounds.mean(axis=0) + inlay.metadata["placements"][0] + assert gp.pocket_floor(inlay, x, y, h) is not None + assert not [v for v in inlay.metadata["wall_check"]["violations"] if v["kind"] == "sealed"] + + def test_short_figure_lowered_by_hand_stays_open(self): + cfg = _cfg() + inlay, w, d, h, _ = _build( + [_box(10, 10, 40), _box(10, 10, 8)], cfg, + individual_offsets=[(0, 0, 0), (0, 0, -14.0)], + ) + assert gp.shell_count(inlay) == 1 + + +class TestRotation: + def test_rotated_figures_do_not_merge(self): + """The web app laid out the *unrotated* figures: two bars turned by + rot_y = 90 overlapped by 18 mm, badge green (review R3/B5).""" + cfg = _cfg(figure_gap=2.0, layout_style="horizontal") + base = [_box(10, 10, 30), _box(10, 10, 30)] + rotated = [inlayer.apply_euler_rotation(m, 0, 90, 0) for m in base] + inlay, w, d, h, _ = _build(rotated, cfg, sorting_reference=base) + assert len(gp.cavities(inlay, w, d, h)) == 2 + assert gp.inner_gap(inlay, w, d, h) == pytest.approx(2.0, abs=TOL) + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + def test_rotated_figure_off_the_origin_gets_a_tight_box(self): + """A block at XY (100, 50) turned by rot_z = 90 got a 170 x 70 mm box + instead of ~26 x 16 mm (review B6).""" + cfg = _cfg() + far = inlayer.apply_euler_rotation(_box(20, 10, 30, at=(100, 50, 0)), 0, 0, 90) + near = inlayer.apply_euler_rotation(_box(20, 10, 30), 0, 0, 90) + inlay, w, d, h, _ = _build([far], cfg) + assert (w, d, h) == pytest.approx(_build([near], cfg)[1:4], abs=TOL) + assert w < d # turned: now 10 wide, 20 deep + assert gp.outer_walls(inlay, w, d, h)["side"] == pytest.approx(cfg.wall_thickness, abs=TOL) + + +class TestFingerRecesses: + """Defaults (r = 8 mm) on purpose: the older tests used r = 1.5 with 4 mm + walls, which is exactly why the breakthroughs went unnoticed.""" + + def _cfg(self, **overrides): + return _cfg(enable_finger_recesses=True, **overrides) + + def test_flat_figure_keeps_its_floor(self): + """30 x 30 x 6 mm: the recesses cut through the floor (review B10).""" + inlay, w, d, h, _ = _build([_box(30, 30, 6)], self._cfg()) + assert gp.outer_walls(inlay, w, d, h)["floor"] >= 2.0 - TOL + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + @pytest.mark.parametrize("axis", ["x", "y"]) + def test_narrow_figure_keeps_its_side_walls(self, axis): + """A 60 x 10 mm bar: recesses 16 mm wide cut through the front and back + wall - the box was only padded along the recess axis (review B11).""" + bar = _box(60, 10, 10) if axis == "x" else _box(10, 60, 10) + inlay, w, d, h, _ = _build([bar], self._cfg(finger_recess_axis=axis)) + assert gp.outer_walls(inlay, w, d, h)["side"] >= 2.0 - TOL + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + def test_lowered_recess_is_open_at_the_top(self): + """With a Z offset the bare hemisphere had a roof: the opening in the + top face stayed exactly as large as without recesses (review B12).""" + z_offset, r = 6.0, 8.0 + inlay, w, d, h, _ = _build([_box(20, 20, 20)], self._cfg(finger_recess_z_offset=z_offset)) + for recess in inlay.metadata["finger_recesses"]: + centre = recess.bounds.mean(axis=0) + # Half a radius outwards: inside the recess, outside the figure + outwards = np.sign(centre[0] - w / 2) * r / 2 + floor = gp.pocket_floor(inlay, centre[0] + outwards, centre[1], h) + assert floor is not None + expected = h - z_offset - np.sqrt(r**2 - (r / 2) ** 2) + assert floor == pytest.approx(expected, abs=0.2) + + def test_neighbours_keep_the_gap_to_each_others_recesses(self): + """Two 6 mm wide figures: each recess overlapped the neighbour's + cavity and recess (review finder).""" + cfg = self._cfg(figure_gap=2.0, layout_style="horizontal", finger_recess_axis="y") + inlay, w, d, h, _ = _build([_box(6, 30, 10), _box(6, 30, 10)], cfg) + assert gp.inner_gap(inlay, w, d, h) >= 2.0 - TOL + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + def test_manual_box_width_is_kept_with_recesses(self): + """Five cubes packed for a 70 mm box needed 98 mm (review B14).""" + cfg = self._cfg(voxel_pitch=1.0, clearance=1.0, figure_gap=2.0, box_width=70.0, + finger_radius=5.0) + inlay, w, d, h, _ = _build([_box(10, 10, 10) for _ in range(5)], cfg) + assert w == 70.0 + assert gp.outer_walls(inlay, w, d, h)["side"] >= 2.0 - TOL + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + +class TestWallCheckIsHonest: + """The check reports what the oracle measures (review R7/B8).""" + + @pytest.mark.parametrize("offset_x", [0.5, 1.0, 1.4, 2.5]) + def test_check_matches_the_measured_side_wall(self, offset_x): + cfg = _cfg(voxel_pitch=1.0) + inlay, w, d, h, _ = _build([_box(10, 10, 10)], cfg, individual_offsets=[(offset_x, 0, 0)]) + measured = gp.outer_walls(inlay, w, d, h)["side"] + check = inlay.metadata["wall_check"] + assert check["min_wall_mm"] == pytest.approx(measured, abs=0.01) + assert check["passes_min_wall"] is (measured >= cfg.wall_thickness - TOL) diff --git a/tests/test_geometry_probe.py b/tests/test_geometry_probe.py new file mode 100644 index 0000000..9a60b6a --- /dev/null +++ b/tests/test_geometry_probe.py @@ -0,0 +1,71 @@ +"""The measuring tool itself, on shapes with known walls. + +geometry_probe is the oracle of the invariant tests; if it measured wrong, +they would pass for the wrong reason. Each case is built by hand with +manifold3d, independent of the pipeline. +""" + +from __future__ import annotations + +import pytest +import trimesh +from manifold3d import Manifold + +from tests import geometry_probe as gp + + +def _trimesh(m: Manifold) -> trimesh.Trimesh: + mesh = m.to_mesh() + return trimesh.Trimesh(vertices=mesh.vert_properties[:, :3], faces=mesh.tri_verts, process=False) + + +def _pocket(x, y, w, d, z, h=20.0) -> Manifold: + """A pocket from z upwards, open at the top of a 10 mm high box.""" + return Manifold.cube((w, d, h)).translate((x, y, z)) + + +BOX = Manifold.cube((30.0, 20.0, 10.0)) + + +def test_outer_walls_of_a_single_pocket(): + inlay = _trimesh(BOX - _pocket(4.0, 5.0, 10.0, 8.0, 3.0)) + walls = gp.outer_walls(inlay, 30.0, 20.0, 10.0) + assert walls["side"] == pytest.approx(4.0, abs=1e-3) # x: 4 left, 16 right; y: 5 / 7 + assert walls["floor"] == pytest.approx(3.0, abs=1e-3) + + +def test_breakthrough_reads_as_no_wall(): + inlay = _trimesh(BOX - _pocket(-1.0, 5.0, 10.0, 8.0, 3.0)) + assert gp.outer_walls(inlay, 30.0, 20.0, 10.0)["side"] < 0.01 + + +def test_inner_gap_and_cavity_count(): + inlay = _trimesh(BOX - _pocket(3.0, 5.0, 8.0, 8.0, 2.0) - _pocket(14.5, 5.0, 8.0, 8.0, 2.0)) + assert len(gp.cavities(inlay, 30.0, 20.0, 10.0)) == 2 + assert gp.inner_gap(inlay, 30.0, 20.0, 10.0) == pytest.approx(3.5, abs=1e-3) + + +def test_sealed_void_is_a_second_shell(): + void = Manifold.cube((4.0, 4.0, 4.0)).translate((10.0, 8.0, 3.0)) + assert gp.shell_count(_trimesh(BOX)) == 1 + assert gp.shell_count(_trimesh(BOX - void)) == 2 + + +def test_pocket_floor_by_ray(): + inlay = _trimesh(BOX - _pocket(4.0, 5.0, 10.0, 8.0, 3.0)) + assert gp.pocket_floor(inlay, 9.0, 9.0, 10.0) == pytest.approx(3.0, abs=1e-4) + assert gp.pocket_floor(inlay, 25.0, 9.0, 10.0) is None # closed top there + + +@pytest.mark.parametrize("sections", [64, 91]) +def test_cylinder_side_wall(sections): + """Odd section counts put a corner on one side and a flat on the other.""" + import math + + radius = 15.0 + cyl = Manifold.cylinder(10.0, radius, circular_segments=sections) + pocket = Manifold.cube((8.0, 6.0, 20.0)).translate((-4.0, -3.0, 2.0)) + inlay = _trimesh(cyl - pocket) + apothem = radius * math.cos(math.pi / sections) + expected = apothem - math.hypot(4.0, 3.0) + assert gp.cylinder_side_wall(inlay) == pytest.approx(expected, abs=1e-3) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 7612341..d474aec 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -31,6 +31,15 @@ "app.layout.compact", "app.layout.horizontal", "app.layout.vertical", + "app.finger.axis.x", + "app.finger.axis.y", + # inlayer.describe_violation: t_(f"check.{kind}") + "check.side", + "check.floor", + "check.inner", + "check.merged", + "check.sealed", + "check.no_cavity", ) @@ -167,6 +176,12 @@ def test_unknown_falls_back_without_raising(self): def test_default_language_is_supported(self): assert i18n.DEFAULT_LANGUAGE in i18n.LANGUAGES + def test_suite_pins_the_environment_too(self): + """CLI subprocesses inherit the environment, not the ContextVar.""" + import os + + assert os.environ[i18n.ENV_VAR] == "en" + def test_language_from_env(self, monkeypatch): monkeypatch.setenv(i18n.ENV_VAR, "de") assert i18n.language_from_env() == "de" diff --git a/tests/test_parallel.py b/tests/test_parallel.py index d9b990e..43e1afb 100644 --- a/tests/test_parallel.py +++ b/tests/test_parallel.py @@ -61,6 +61,22 @@ def boom(_x): with pytest.raises(ValueError, match="kaputt"): inlayer._parallel_map(boom, [1, 2, 3], cfg) + def test_worker_init_runs_in_every_worker_and_keeps_the_language(self): + """The web app attaches Streamlit's context through worker_init. Its own + pool used to skip the language hand-over (review N12).""" + import threading + + import i18n + + i18n.set_language("de") + initialised = set() + seen = inlayer._parallel_map( + lambda _: (threading.get_ident() in initialised, i18n.get_language()), + range(8), Config(enable_parallel=True), + worker_init=lambda: initialised.add(threading.get_ident()), + ) + assert seen == [(True, "de")] * 8 + def test_parallel_logt_worker_anzahl(self, capsys): cfg = Config(enable_parallel=True) inlayer._parallel_map(lambda x: x, range(4), cfg, what="Test") @@ -131,9 +147,7 @@ class TestBuildInlayParallel: def test_parallel_liefert_gleiches_ergebnis( self, dilated_cube, dilated_sphere, fast_test_config, capsys ): - arranged = inlayer.arrange_figures( - [dilated_cube, dilated_sphere], gap=fast_test_config.wall_thickness - ) + arranged = [dilated_cube, dilated_sphere] cfg_par = dataclasses.replace(fast_test_config, enable_parallel=True) inlay_seq, w1, d1, h1 = inlayer.build_inlay(arranged, fast_test_config) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index afd87c7..193eb01 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -26,7 +26,7 @@ def test_cube_pipeline_end_to_end(self, cube_stl_path, fast_test_config): fig = inlayer.prepare_figure(cube_stl_path, fast_test_config) fig_ot = inlayer.dilate(fig, fast_test_config.clearance, fast_test_config) inlay, w, d, h = inlayer.build_inlay(fig_ot, fast_test_config) - stats = inlayer.wall_thickness_stats_3d(inlay, fast_test_config) + stats = inlayer.wall_thickness_stats_3d(inlay) assert inlay.is_watertight or len(inlay.faces) > 0 assert stats["passes_min_wall"] is True @@ -43,7 +43,7 @@ def test_sphere_pipeline_end_to_end(self, sphere_stl_path, fast_test_config): fig = inlayer.prepare_figure(sphere_stl_path, fast_test_config) fig_ot = inlayer.dilate(fig, fast_test_config.clearance, fast_test_config) inlay, *_ = inlayer.build_inlay(fig_ot, fast_test_config) - stats = inlayer.wall_thickness_stats_3d(inlay, fast_test_config) + stats = inlayer.wall_thickness_stats_3d(inlay) assert stats["passes_min_wall"] is True def test_inlay_exports_to_stl(self, cube_stl_path, fast_test_config, tmp_path): @@ -202,27 +202,88 @@ def test_cli_recess_position_count_mismatch_fails(self, cube_stl_path, sphere_st assert result.returncode != 0 assert "--finger-recess-position" in result.stderr - def test_cli_recess_position_out_of_range_fails(self, cube_stl_path, tmp_path): - """A position beyond +/-1.0 is rejected before anything is written.""" + def test_cli_recess_position_out_of_range_fails(self, cube_stl_path, sphere_stl_path, tmp_path): + """Every value is checked while parsing - the second one used to fail + only inside build_inlay, with a traceback after minutes of work.""" out = tmp_path / "inlay.stl" result = subprocess.run( [ sys.executable, str(REPO_ROOT / "inlayer.py"), - "-i", cube_stl_path, + "-i", cube_stl_path, sphere_stl_path, "-o", str(out), "-vp", "1.0", "--decimate-faces", "1000", "--finger-recesses", - "--finger-recess-position", "2.0", + "--finger-recess-position", "0.5", "2.0", ], capture_output=True, text=True, timeout=120, ) - assert result.returncode != 0 + assert result.returncode == 2 # argparse usage error + assert "Traceback" not in result.stderr + assert "[1/4]" not in result.stdout # no pipeline step ran assert not out.exists() + def test_cli_recess_count_is_only_checked_with_recesses(self, cube_stl_path, tmp_path): + """Without --finger-recesses the positions have no effect: a note, no error.""" + out = tmp_path / "inlay.stl" + result = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "inlayer.py"), + "-i", cube_stl_path, + "-o", str(out), + "-vp", "1.0", + "--decimate-faces", "1000", + "--finger-recess-position", "0.1", "0.2", "0.3", + ], + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stderr + assert "ignored" in result.stdout + + def test_cli_failed_check_exits_with_3_and_names_the_file(self, cube_stl_path, tmp_path): + """A thin wall used to end in exit code 0 and printable scrap.""" + out = tmp_path / "inlay.stl" + result = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "inlayer.py"), + "-i", cube_stl_path, + "-o", str(out), + "-vp", "1.0", + "--decimate-faces", "1000", + "--box-width", "14", + ], + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 3, result.stdout + assert "cube.stl" in result.stdout and "side wall" in result.stdout + assert out.exists() # written anyway, to be inspected + + def test_cli_passing_check_exits_with_0(self, cube_stl_path, tmp_path): + result = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "inlayer.py"), + "-i", cube_stl_path, + "-o", str(tmp_path / "inlay.stl"), + "-vp", "1.0", + "--decimate-faces", "1000", + ], + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "Success" in result.stdout + def test_cli_missing_input_fails(self, tmp_path): result = subprocess.run( [ @@ -242,7 +303,7 @@ def test_cli_missing_input_fails(self, tmp_path): assert "nicht gefunden" in combined or "FileNotFoundError" in combined def test_cli_invalid_param_fails(self, cube_stl_path, tmp_path): - # clearance darf nicht negativ sein -> Config-Validierung wirft ValueError. + """An invalid value is a usage error naming the field, not a traceback.""" result = subprocess.run( [ sys.executable, @@ -255,10 +316,24 @@ def test_cli_invalid_param_fails(self, cube_stl_path, tmp_path): text=True, timeout=30, ) - assert result.returncode != 0 - assert "ValueError" in result.stderr or "clearance" in ( - result.stdout + result.stderr + assert result.returncode == 2 + assert "clearance" in result.stderr + assert "Traceback" not in result.stderr + + @pytest.mark.parametrize( + "flag,value,message", + [("-df", "1.5", "depth_fraction must be > 0 and <= 1"), + ("-w", "nan", "wall_thickness must be a finite number")], + ) + def test_cli_out_of_range_value_is_a_usage_error(self, cube_stl_path, tmp_path, flag, value, message): + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "inlayer.py"), "-i", cube_stl_path, + "-o", str(tmp_path / "inlay.stl"), flag, value], + capture_output=True, text=True, timeout=30, ) + assert result.returncode == 2 + assert message in result.stderr + assert "Traceback" not in result.stderr @pytest.mark.slow @@ -273,14 +348,10 @@ def test_cube_sphere_pipeline(self, cube_stl_path, sphere_stl_path, fast_test_co ot1 = inlayer.dilate(fig1, fast_test_config.clearance, fast_test_config) ot2 = inlayer.dilate(fig2, fast_test_config.clearance, fast_test_config) - gap = fast_test_config.wall_thickness - arranged = inlayer.arrange_figures([ot1, ot2], gap) - assert len(arranged) == 2 - - inlay, w, d, h = inlayer.build_inlay(arranged, fast_test_config) + inlay, w, d, h = inlayer.build_inlay([ot1, ot2], fast_test_config) assert len(inlay.faces) > 0 - stats = inlayer.wall_thickness_stats_3d(inlay, fast_test_config) + stats = inlayer.wall_thickness_stats_3d(inlay) assert stats["passes_min_wall"] is True def test_cli_multi_input(self, cube_stl_path, sphere_stl_path, tmp_path): diff --git a/tests/test_prepare_figure.py b/tests/test_prepare_figure.py index c31d7ce..72315db 100644 --- a/tests/test_prepare_figure.py +++ b/tests/test_prepare_figure.py @@ -12,7 +12,7 @@ class TestPrepareFigureErrors: def test_missing_file_raises_filenotfound(self, tmp_path): - with pytest.raises(FileNotFoundError, match="nicht gefunden"): + with pytest.raises(FileNotFoundError, match="not found"): inlayer.prepare_figure(str(tmp_path / "nope.stl")) def test_directory_path_raises_filenotfound(self, tmp_path): @@ -20,6 +20,125 @@ def test_directory_path_raises_filenotfound(self, tmp_path): with pytest.raises(FileNotFoundError): inlayer.prepare_figure(str(tmp_path)) + @pytest.mark.parametrize( + "content", + [b"", bytes(84), np.random.default_rng(0).bytes(500)], + ids=["zero-bytes", "header-without-triangles", "random-bytes"], + ) + def test_empty_or_garbled_file_names_the_file(self, tmp_path, content): + """trimesh returns an empty mesh instead of raising; that used to end in + a cryptic `'NoneType' object has no attribute 'round'` far downstream.""" + path = tmp_path / "broken.stl" + path.write_bytes(content) + with pytest.raises(ValueError, match="broken.stl.*no triangles"): + inlayer.prepare_figure(str(path)) + + def test_oversized_grid_is_refused_up_front(self, cube_stl_path): + """A small file scaled up must fail with a message, not exhaust memory.""" + cfg = Config(stl_unit_to_mm=1000.0, voxel_pitch=0.2) + with pytest.raises(ValueError, match="too large"): + inlayer.prepare_figure(cube_stl_path, cfg) + + +class TestPrepareFigureKeepsEveryShell: + """pymeshfix's default repair kept only the shell with the most triangles. + + Whether a part survived depended on an unrelated hole anywhere in the file: + a watertight two-shell file skipped the repair and kept both, the same file + with one missing triangle lost everything but its largest shell. + """ + + @staticmethod + def _holed_box(extents, at): + box = trimesh.creation.box(extents=extents) + box.apply_translation(at) + keep = np.ones(len(box.faces), dtype=bool) + keep[0] = False # one missing triangle forces the repair + return trimesh.Trimesh(vertices=box.vertices, faces=box.faces[keep], process=False) + + def _prepare(self, tmp_path, parts, cfg): + path = tmp_path / "parts.stl" + trimesh.util.concatenate(parts).export(file_obj=str(path), file_type="stl") + return inlayer.prepare_figure(str(path), cfg) + + def test_holed_body_keeps_its_separate_base(self, tmp_path, fast_test_config): + base = trimesh.creation.cylinder(radius=12.5, height=3.0, sections=64) + body = self._holed_box([8.0, 8.0, 20.0], [0.0, 0.0, 12.0]) + m = self._prepare(tmp_path, [base, body], fast_test_config) + # Base: 25 mm wide, 3 mm high; body: reaches up to z = 22 mm. The + # default repair kept only the shell with more triangles (the base). + assert m.extents[0] > 24.0 and m.extents[1] > 24.0 + assert m.extents[2] > 20.0 + + def test_holed_large_part_survives_next_to_a_small_intact_one(self, tmp_path, fast_test_config): + big = self._holed_box([20.0, 20.0, 30.0], [0.0, 0.0, 0.0]) + small = trimesh.creation.box(extents=[4.0, 4.0, 25.0]) + small.apply_translation([20.0, 0.0, 0.0]) + m = self._prepare(tmp_path, [big, small], fast_test_config) + # The default repair sorted by triangle count and kept only the 4x4 part + assert m.extents[0] > 30.0 and m.extents[2] > 29.0 + + +class TestVoxelizeSurface: + """_voxelize_surface replaces trimesh's subdivision voxelizer for raw input. + + trimesh quarters each triangle until all edges are below pitch / 2, so a + long, thin triangle costs (length / pitch)² however little area it has. + """ + + @staticmethod + def _occupied(vox) -> set[tuple[int, int, int]]: + origin = np.round(vox.transform[:3, 3] / vox.transform[0, 0]).astype(int) + return {tuple(ix + origin) for ix in np.argwhere(vox.matrix)} + + def test_matches_trimesh_on_a_regular_mesh(self): + sphere = trimesh.creation.icosphere(subdivisions=4, radius=10.0) + ours = self._occupied(inlayer._voxelize_surface(sphere, 0.5)) + theirs = self._occupied(sphere.voxelized(pitch=0.5)) + # Same surface, same rounding: they may differ by the odd voxel where + # the surface grazes a voxel boundary, not by whole layers. + assert len(ours ^ theirs) < 0.05 * len(theirs) + + def test_face_on_a_rounding_boundary_stays_put(self): + """A 10 mm cube at pitch 0.4 has its faces on the .5 of the rounding; + one ulp of interpolation noise there flipped a whole voxel layer.""" + cube = trimesh.creation.box(extents=[10.0, 10.0, 10.0]) + ours = self._occupied(inlayer._voxelize_surface(cube, 0.4)) + assert ours == self._occupied(cube.voxelized(pitch=0.4)) + + def test_filled_sphere_has_the_sphere_volume(self): + sphere = trimesh.creation.icosphere(subdivisions=4, radius=10.0) + ours = inlayer._voxelize_surface(sphere, 0.5) + ours.fill() + theirs = sphere.voxelized(pitch=0.5) + theirs.fill() + # A leaking shell would leave the interior empty (volume of a skin only); + # both count the whole boundary layer, hence trimesh as the reference + # rather than the analytic volume. + assert ours.matrix.sum() == pytest.approx(theirs.matrix.sum(), rel=0.02) + assert ours.matrix.sum() * 0.5**3 > 0.9 * sphere.volume + + def test_long_thin_triangles_stay_cheap(self): + """A 256-triangle rod took 1.95 GB and 13 s through trimesh (review B17).""" + import tracemalloc + + rod = trimesh.creation.cylinder(radius=4.0, height=120.0, sections=128) + tracemalloc.start() + vox = inlayer._voxelize_surface(rod, 0.4) + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + assert peak < 200 * 1024**2 + assert vox.matrix.shape[2] >= 120 / 0.4 + + def test_low_poly_bar_no_longer_aborts(self, tmp_path): + """A 12-triangle 250 mm bar ended in 'max_iter exceeded' (review B16).""" + bar = trimesh.creation.box(extents=[250.0, 10.0, 10.0]) + path = tmp_path / "bar.stl" + bar.export(file_obj=str(path), file_type="stl") + m = inlayer.prepare_figure(str(path), Config(voxel_pitch=0.4, decimate_faces=1000)) + assert m.is_watertight + assert m.extents[0] == pytest.approx(250.0, abs=1.0) + class TestPrepareFigureBasic: def test_returns_trimesh(self, cube_stl_path, fast_test_config): diff --git a/tests/test_streamlit_config.py b/tests/test_streamlit_config.py index 869ab51..0dab55c 100644 --- a/tests/test_streamlit_config.py +++ b/tests/test_streamlit_config.py @@ -8,6 +8,8 @@ from __future__ import annotations +import ast +import re import tomllib from pathlib import Path @@ -38,10 +40,73 @@ def test_theme_stays_dark(): assert _config()["theme"]["base"] == "dark" -def test_dockerfile_copies_streamlit_config(): - """Without that COPY line neither theme nor upload limit reach the container.""" +def _stages(dockerfile: str) -> dict[str, str]: + """The Dockerfile split into its stages, by `FROM ... AS `.""" + stages: dict[str, str] = {} + name = None + for line in dockerfile.splitlines(): + match = re.match(r"\s*FROM\s+\S+\s+AS\s+(\S+)", line, re.IGNORECASE) + if match: + name = match.group(1) + stages[name] = "" + elif name is not None: + stages[name] += line + "\n" + return stages + + +def _copied(stage: str) -> set[str]: + """Sources of every COPY in a stage (the last argument is the target).""" + sources: set[str] = set() + for line in stage.splitlines(): + parts = line.split() + if parts and parts[0].upper() == "COPY": + sources.update(p.rstrip("/") for p in parts[1:-1] if not p.startswith("--")) + return sources + + +def _repo_imports(module: str, seen: set[str] | None = None) -> set[str]: + """Repo modules `module` imports, transitively (read from the source).""" + seen = set() if seen is None else seen + tree = ast.parse((_REPO_ROOT / f"{module}.py").read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.module: + names = [node.module] + else: + continue + for root in (n.split(".")[0] for n in names): + if root not in seen and (_REPO_ROOT / f"{root}.py").is_file(): + seen.add(root) + _repo_imports(root, seen) + return seen + + +def _missing_in_runtime(dockerfile: str) -> set[str]: + """What the runtime image needs to run app.py but does not copy.""" + needed = {"app.py", ".streamlit"} | {f"{m}.py" for m in _repo_imports("app")} + return needed - _copied(_stages(dockerfile).get("runtime", "")) + + +def test_runtime_stage_ships_the_app(): + """Without its modules the app does not start, without .streamlit/ it runs + in the light theme with the upload default. The runtime stage is what + compose builds - CI builds it too, but this names the missing file.""" dockerfile = (_REPO_ROOT / "Dockerfile").read_text(encoding="utf-8") - assert "COPY .streamlit/" in dockerfile + assert _missing_in_runtime(dockerfile) == set() + + +def test_runtime_check_looks_at_the_runtime_stage_only(): + """The earlier check searched the whole file for "COPY .streamlit/" - the + test stage's copy of it satisfied that on its own (review N3).""" + dockerfile = (_REPO_ROOT / "Dockerfile").read_text(encoding="utf-8") + runtime = _stages(dockerfile)["runtime"] + stripped = dockerfile.replace( + runtime, runtime.replace("COPY .streamlit/ ./.streamlit/", "") + ) + assert "COPY .streamlit/" in stripped # still there in the test stage + assert _missing_in_runtime(stripped) == {".streamlit"} + assert "i18n.py" in _missing_in_runtime(stripped.replace(" i18n.py", "")) def test_no_deprecated_use_container_width_api(): diff --git a/tests/test_wall_thickness.py b/tests/test_wall_thickness.py index 1342c7a..2bc338d 100644 --- a/tests/test_wall_thickness.py +++ b/tests/test_wall_thickness.py @@ -1,228 +1,140 @@ -"""Tests fuer inlayer.wall_thickness_stats_3d.""" +"""Tests for the wall check that build_inlay runs and wall_thickness_stats_3d reports. + +The check measures the real cutters with manifold3d. Its predecessor +rasterized the cavities: it overestimated walls by up to a pitch, never looked +at the walls between cavities, passed an inlay without any cavity and blamed +no figure for a recess breaking through. +""" from __future__ import annotations -import numpy as np import pytest import trimesh +from manifold3d import Manifold +import i18n import inlayer from inlayer import Config +from tests import geometry_probe as gp +TOL = inlayer.WALL_TOLERANCE_MM +CFG = Config(voxel_pitch=1.0, decimate_faces=1000, clearance=0.5) -class TestWallThicknessSchema: - def test_returns_expected_keys(self, inlay_for_cube, fast_test_config): - stats = inlayer.wall_thickness_stats_3d(inlay_for_cube, fast_test_config) - assert set(stats.keys()) == { - "min_wall_mm", - "passes_min_wall", - "target_mm", - } - def test_values_have_correct_types(self, inlay_for_cube, fast_test_config): - stats = inlayer.wall_thickness_stats_3d(inlay_for_cube, fast_test_config) - assert isinstance(stats["min_wall_mm"], float) - assert isinstance(stats["passes_min_wall"], (bool, type(True))) - assert stats["target_mm"] == fast_test_config.wall_thickness +def _build(meshes, cfg=CFG, **kwargs): + inlay, w, d, h = inlayer.build_inlay(meshes, cfg, **kwargs) + return inlay, w, d, h -class TestWallThicknessValues: - def test_min_wall_non_negative(self, inlay_for_cube, fast_test_config): - stats = inlayer.wall_thickness_stats_3d(inlay_for_cube, fast_test_config) - assert stats["min_wall_mm"] >= 0.0 +def _kinds(inlay) -> list[tuple[str, int | None]]: + return [(v["kind"], v["figure"]) for v in inlay.metadata["wall_check"]["violations"]] - def test_default_inlay_passes_min_wall(self, inlay_for_cube, fast_test_config): - # Der Standard-Workflow sollte die Wandstaerken-Anforderung erfuellen. - stats = inlayer.wall_thickness_stats_3d(inlay_for_cube, fast_test_config) - assert stats["passes_min_wall"] is True - - def test_min_wall_close_to_target(self, inlay_for_cube, fast_test_config): - # Bei automatischer Box-Dimensionierung sollte die minimale Wand - # nahe der konfigurierten Soll-Wandstaerke liegen - # (kann durch Voxel-Diskretisierung leicht groesser sein). - stats = inlayer.wall_thickness_stats_3d(inlay_for_cube, fast_test_config) - # Untere Schranke: target - 0.1 (Toleranz im Quellcode) - assert stats["min_wall_mm"] >= fast_test_config.wall_thickness - 0.1 - - -class TestWallThicknessPassThreshold: - def test_threshold_uses_voxel_tolerance(self, dilated_cube): - # Konstruiere ein Inlay mit einer wall_thickness, die exakt erreicht wird, - # und pruefe, dass die 0.1 mm Voxel-Toleranz greift. - cfg = Config(wall_thickness=2.0, voxel_pitch=1.0, decimate_faces=1000) - inlay, *_ = inlayer.build_inlay(dilated_cube, cfg) - stats = inlayer.wall_thickness_stats_3d(inlay, cfg) - # passes_min_wall: True wenn min_wall >= target - 0.1 - expected_pass = stats["min_wall_mm"] >= cfg.wall_thickness - 0.1 - assert stats["passes_min_wall"] == expected_pass - - def test_strict_higher_target_likely_fails(self, dilated_cube, fast_test_config): - # Wenn die Box-Dimensionen mit wall_thickness=2.0 berechnet wurden, - # aber wir die Stats mit wall_thickness=10.0 nachrechnen, sollte - # passes_min_wall=False sein. - inlay, *_ = inlayer.build_inlay(dilated_cube, fast_test_config) - strict_cfg = Config( - wall_thickness=10.0, - voxel_pitch=fast_test_config.voxel_pitch, - decimate_faces=fast_test_config.decimate_faces, - ) - stats = inlayer.wall_thickness_stats_3d(inlay, strict_cfg) - assert stats["passes_min_wall"] is False - assert stats["target_mm"] == 10.0 - - -class TestWallThicknessOffCenter: - def test_off_center_figure_reports_thin_wall(self, dilated_cube): - # Regressionstest: Die Messung nutzt die Voxelgitter-Kanten als Box-Waende. - # Das ist nur korrekt, weil trimesh die Voxelzentren exakt auf die - # Mesh-Bounds legt und die Inlay-Bounds immer den Box-Waenden entsprechen. - # Eine aussermittige Figur (duenne rechte Wand) muss korrekt gemessen werden. - cfg = Config( - wall_thickness=2.0, voxel_pitch=0.5, decimate_faces=1000, box_width=20.0 - ) - inlay, box_w, *_ = inlayer.build_inlay( - dilated_cube, cfg, individual_offsets=[(3.0, 0.0, 0.0)] - ) - stats = inlayer.wall_thickness_stats_3d(inlay, cfg) - # Geometrische Erwartung fuer die rechte Wand: - # halbe Box-Breite minus halbe dilatierte Figurbreite minus X-Offset - expected = box_w / 2 - dilated_cube.extents[0] / 2 - 3.0 - assert stats["min_wall_mm"] == pytest.approx(expected, abs=2 * cfg.voxel_pitch) - assert stats["passes_min_wall"] is False - - -class TestWallThicknessCavityGrid: - def test_grid_contains_every_figure(self, dilated_cube, fast_test_config): - # Regressionstest: Das Hohlraum-Gitter wird figurweise gefuellt. Eine - # Begrenzung auf die Bounds einer Figur darf die bereits eingetragenen - # Figuren nicht wieder loeschen, sonst meldet ein Multi-Figur-Inlay nur - # noch den Hohlraum der zuletzt verarbeiteten Figur. - figs = [dilated_cube.copy(), dilated_cube.copy()] - placed = inlayer.arrange_figures(figs, 2.0) - inlay, *_ = inlayer.build_inlay(placed, fast_test_config) - - grid = inlay.metadata["cavity_grid"] - # Die Figuren liegen entlang Y nebeneinander: beide Haelften des Gitters - # muessen Hohlraum enthalten. - haelfte = grid.shape[1] // 2 - assert grid[:, :haelfte, :].any(), "Hohlraum der ersten Figur fehlt" - assert grid[:, haelfte:, :].any(), "Hohlraum der zweiten Figur fehlt" - - def test_multi_figure_wall_matches_single(self, dilated_cube, fast_test_config): - # Zwei gleiche Figuren nebeneinander: die Mindestwandstaerke muss - # dieselbe sein wie bei einer einzelnen Figur. - einzel, *_ = inlayer.build_inlay(dilated_cube, fast_test_config) - erwartet = inlayer.wall_thickness_stats_3d(einzel, fast_test_config) - - placed = inlayer.arrange_figures( - [dilated_cube.copy(), dilated_cube.copy()], 2.0 - ) - multi, *_ = inlayer.build_inlay(placed, fast_test_config) - stats = inlayer.wall_thickness_stats_3d(multi, fast_test_config) - - assert stats["min_wall_mm"] == pytest.approx(erwartet["min_wall_mm"]) - assert stats["passes_min_wall"] is True +class TestSchema: + def test_keys(self, inlay_for_cube): + stats = inlayer.wall_thickness_stats_3d(inlay_for_cube) + assert set(stats) == {"min_wall_mm", "passes_min_wall", "target_mm", "violations"} -class TestWallThicknessSolidFallback: - def test_solid_inlay_uses_fallback(self, fast_test_config): - # Ein massiver Wuerfel hat keinen Hohlraum -> Fallback liefert target_wall. - solid = trimesh.creation.box(extents=[20.0, 20.0, 20.0]) - stats = inlayer.wall_thickness_stats_3d(solid, fast_test_config) - # Im Fallback ist min == wall_thickness - assert stats["min_wall_mm"] == fast_test_config.wall_thickness - assert stats["passes_min_wall"] is True - - -class TestWallThicknessCylinder: - def _cylinder_cfg(self, base: Config, **overrides) -> Config: - params = dict( - clearance=base.clearance, - wall_thickness=base.wall_thickness, - depth_fraction=base.depth_fraction, - voxel_pitch=base.voxel_pitch, - decimate_faces=base.decimate_faces, - box_shape="cylinder", - ) - params.update(overrides) - return Config(**params) - - def test_cylinder_inlay_passes_min_wall(self, dilated_cube, fast_test_config): - # Auto-dimensionierter Zylinder muss die Soll-Wandstaerke einhalten. - cfg = self._cylinder_cfg(fast_test_config) - inlay, *_ = inlayer.build_inlay(dilated_cube, cfg) - stats = inlayer.wall_thickness_stats_3d(inlay, cfg) - assert stats["passes_min_wall"] is True - assert stats["min_wall_mm"] >= cfg.wall_thickness - 0.1 - - def test_grid_corners_are_not_cavity(self, fast_test_config): - # Regressionstest: Die Gitterecken des Voxelgrids liegen ausserhalb des - # Zylinders und duerfen nicht als Kavitaet mit Wandstaerke ~0 zaehlen. - # Ein massiver Zylinder hat keinen Hohlraum -> Fallback liefert target_wall. - solid = trimesh.creation.cylinder(radius=10.0, height=8.0, sections=128) - cfg = self._cylinder_cfg(fast_test_config) - stats = inlayer.wall_thickness_stats_3d(solid, cfg) - assert stats["min_wall_mm"] == cfg.wall_thickness + def test_types_and_default_result(self, inlay_for_cube, fast_test_config): + stats = inlayer.wall_thickness_stats_3d(inlay_for_cube) + assert isinstance(stats["min_wall_mm"], float) assert stats["passes_min_wall"] is True - - def test_off_center_figure_fails_radial_check(self, dilated_cube, fast_test_config): - # Eine radial verschobene Figur reisst die Zylinderwand an -> Messung - # muss die Unterschreitung erkennen. - cfg = self._cylinder_cfg(fast_test_config) - inlay, *_ = inlayer.build_inlay( - dilated_cube, cfg, individual_offsets=[(3.0, 0.0, 0.0)] - ) - stats = inlayer.wall_thickness_stats_3d(inlay, cfg) - assert stats["passes_min_wall"] is False - - -class TestFloorThicknessStableBounds: - """Regression: die Bodenwand darf nicht am Padding der stabilen Bounds haengen. - - Die Bounds aus arrange_with_stable_bounds waren in Z um - clearance + voxel_pitch je Seite erweitert. Dieser Zuschlag floss ueber - max_z_extent voll in Box-Hoehe und Figuren-Position ein und machte den Boden - um bis zu 2 * (clearance + voxel_pitch) dicker als konfiguriert. Richtig ist - voxel_pitch/2 je Seite – die Inflation, die _solidify_figure auftraegt. - """ - - def _build_via_stable_bounds(self, mesh, cfg): - dilated = inlayer.dilate(mesh, cfg.clearance, cfg) - arranged, bounds, _ = inlayer.arrange_with_stable_bounds( - [mesh], [mesh], [dilated], cfg - ) - inlay, _, _, box_h = inlayer.build_inlay( - arranged, cfg, stable_global_bounds=bounds - ) - return inlay, box_h, dilated - - def _floor_mm(self, inlay, cfg): - """Bodenwand aus dem Kavitaets-Gitter (auf voxel_pitch quantisiert).""" - grid = inlay.metadata["cavity_grid"] - occupied_z = np.where(grid.any(axis=(0, 1)))[0] - return float(occupied_z.min()) * cfg.voxel_pitch - - def test_floor_stays_near_wall_thickness(self, cube_mesh, fast_test_config): - inlay, _, _ = self._build_via_stable_bounds(cube_mesh, fast_test_config) - floor = self._floor_mm(inlay, fast_test_config) - wt = fast_test_config.wall_thickness - # Untergrenze: die konfigurierte Wandstaerke (mit Voxel-Toleranz). - assert floor >= wt - 0.1 - # Obergrenze: hoechstens ein Voxel Schlupf. Mit dem alten Padding lag - # der Boden hier bei 5.0 mm statt 2.0 mm. - assert floor <= wt + fast_test_config.voxel_pitch + 0.1 - - def test_box_height_uses_solidify_compensation_only(self, cube_mesh, fast_test_config): - cfg = fast_test_config - _, box_h, dilated = self._build_via_stable_bounds(cube_mesh, cfg) - expected_z = dilated.extents[2] + cfg.voxel_pitch - assert box_h == pytest.approx( - cfg.wall_thickness + cfg.depth_fraction * expected_z, abs=1e-6 - ) - - def test_stable_and_plain_path_agree_on_height(self, cube_mesh, fast_test_config): - """Beide build_inlay-Pfade muessen dieselbe Box-Hoehe liefern.""" - cfg = fast_test_config - _, box_h_stable, dilated = self._build_via_stable_bounds(cube_mesh, cfg) - _, _, _, box_h_plain = inlayer.build_inlay([dilated.copy()], cfg) - assert box_h_stable == pytest.approx(box_h_plain, abs=1e-6) + assert stats["violations"] == [] + assert stats["target_mm"] == fast_test_config.wall_thickness + assert stats["min_wall_mm"] == pytest.approx(fast_test_config.wall_thickness, abs=TOL) + + def test_needs_the_metadata_of_build_inlay(self): + """A plain mesh carries no check; guessing one from a voxel grid was + exactly the inaccurate path this replaces.""" + with pytest.raises(ValueError, match="build_inlay"): + inlayer.wall_thickness_stats_3d(trimesh.creation.box(extents=[20, 20, 20])) + + +class TestFindings: + """Every kind of finding, attributed to the figure it belongs to.""" + + def test_side(self, dilated_cube): + inlay, w, d, h = _build([dilated_cube], individual_offsets=[(1.5, 0.0, 0.0)]) + assert _kinds(inlay) == [("side", 0)] + measured = inlay.metadata["wall_check"]["violations"][0]["measured_mm"] + assert measured == pytest.approx(gp.outer_walls(inlay, w, d, h)["side"], abs=0.01) + + def test_floor(self, dilated_cube): + inlay, *_ = _build([dilated_cube], Config(voxel_pitch=1.0, decimate_faces=1000, box_height=8.5)) + assert ("floor", 0) in _kinds(inlay) + + def test_inner_names_both_figures(self, dilated_cube): + # figure_gap 4: moving the second figure 3 mm towards the first leaves ~1 mm + cfg = Config(voxel_pitch=1.0, decimate_faces=1000, figure_gap=4.0, layout_style="horizontal") + inlay, w, d, h = _build([dilated_cube, dilated_cube.copy()], cfg, + individual_offsets=[(0, 0, 0), (-3.0, 0, 0)]) + (finding,) = inlay.metadata["wall_check"]["violations"] + assert (finding["kind"], {finding["figure"], finding["other"]}) == ("inner", {0, 1}) + assert finding["measured_mm"] == pytest.approx(gp.inner_gap(inlay, w, d, h), abs=0.01) + assert finding["target_mm"] == 4.0 + + def test_merged(self, dilated_cube): + cfg = Config(voxel_pitch=1.0, decimate_faces=1000, figure_gap=2.0, layout_style="horizontal") + inlay, *_ = _build([dilated_cube, dilated_cube.copy()], cfg, + individual_offsets=[(0, 0, 0), (-6.0, 0, 0)]) + assert ("merged", 0) in _kinds(inlay) + + def test_no_cavity(self, dilated_cube): + """Raised clear of the box: nothing is cut at all. The old check passed + such an inlay because an empty cavity grid had no thin wall.""" + inlay, *_ = _build([dilated_cube], individual_offsets=[(0.0, 0.0, 30.0)]) + assert _kinds(inlay) == [("no_cavity", 0)] + assert inlay.metadata["wall_check"]["passes_min_wall"] is False + + def test_sealed(self): + """build_inlay no longer produces one, so the check is fed by hand.""" + box = Manifold.cube((20.0, 20.0, 10.0)).translate((-10.0, -10.0, -10.0)) + cutter = Manifold.cube((6.0, 6.0, 4.0)).translate((-3.0, -3.0, -7.0)) + check = inlayer._wall_check(box, [cutter], box - cutter, CFG) + assert [(v["kind"], v["figure"]) for v in check["violations"]] == [("sealed", 0)] + + def test_recess_breakthrough_names_its_figure(self, dilated_cube): + """Recesses are part of their figure's cutter; the old check only + reported a blanket "0.00 mm" and no figure.""" + cfg = Config(voxel_pitch=1.0, decimate_faces=1000, enable_finger_recesses=True, + finger_radius=4.0, layout_style="horizontal") + inlay, *_ = _build([dilated_cube, dilated_cube.copy()], cfg, + individual_offsets=[(0, 0, 0), (3.0, 0, 0)]) + assert _kinds(inlay) == [("side", 1)] + + def test_violating_indices_follow_the_findings(self, dilated_cube): + inlay, *_ = _build([dilated_cube, dilated_cube.copy()], + Config(voxel_pitch=1.0, decimate_faces=1000, layout_style="horizontal"), + individual_offsets=[(0, 0, 0), (0.0, 2.0, 0)]) + assert inlay.metadata["violating_indices"] == [1] + + +class TestCylinder: + def _cfg(self): + return Config(voxel_pitch=1.0, decimate_faces=1000, box_shape="cylinder") + + def test_centred_figure_passes(self, dilated_cube): + inlay, *_ = _build([dilated_cube], self._cfg()) + assert inlay.metadata["wall_check"]["passes_min_wall"] is True + + def test_radial_wall_is_measured(self, dilated_cube): + """An off-centre figure cuts into the mantle: the check reports the + real radial wall (the voxel check reported 0.50 for a breakthrough).""" + inlay, *_ = _build([dilated_cube], self._cfg(), individual_offsets=[(3.0, 0.0, 0.0)]) + (finding,) = [v for v in inlay.metadata["wall_check"]["violations"] if v["kind"] == "side"] + assert finding["figure"] == 0 + assert finding["measured_mm"] == pytest.approx(gp.cylinder_side_wall(inlay), abs=0.01) + + +class TestDescribeViolation: + FINDING = {"figure": 1, "kind": "inner", "measured_mm": 0.8, "target_mm": 2.0, "other": 0} + + @pytest.mark.parametrize("lang", sorted(i18n.LANGUAGES)) + def test_names_both_figures_and_values(self, lang): + i18n.set_language(lang) + line = inlayer.describe_violation(self.FINDING, ["a.stl", "b.stl"]) + assert "b.stl" in line and "a.stl" in line and "0.80" in line and "2.00" in line + + def test_unknown_figure_does_not_raise(self): + line = inlayer.describe_violation({**self.FINDING, "kind": "sealed", "figure": None}, []) + assert "#?" in line