mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-08-05 01:02:08 +00:00
Merge branch 'main' into feature/cache_profiles_and_optimize_loading_speed
This commit is contained in:
57
tests/AGENTS.md
Normal file
57
tests/AGENTS.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Test suite rules
|
||||
|
||||
Rules for writing tests under `tests/`. [CATCH2.md](CATCH2.md) is the Catch2 reference. Building and running the suites is covered on the wiki, at <https://www.orcaslicer.com/wiki/developer_reference/how_to_test.html>.
|
||||
|
||||
## The suites
|
||||
|
||||
- `libslic3r`: the core library. Geometry, meshes, file formats, config and presets, Clipper, algorithms, data structures.
|
||||
- `fff_print`: the FFF slicing pipeline, from a `Model` plus config through `Print` and `PrintObject` to emitted G-code.
|
||||
- `sla_print`: SLA support-tree and pad geometry, support-point generation, raycast.
|
||||
- `libnest2d`: 2D nesting and packing.
|
||||
- `slic3rutils`: the Python plugin system and its slicing-pipeline bindings.
|
||||
- `filament_group`: filament-to-extruder grouping, checked against golden files.
|
||||
|
||||
## Building and running
|
||||
|
||||
Tests are off by default, so the build has to be told to include them.
|
||||
|
||||
- Windows: `build_release_vs.bat tests`, then `ctest --test-dir build/tests -C Release`
|
||||
- macOS: `./build_release_macos.sh -s -a arm64 -T`, which builds and runs them
|
||||
- Linux: `./build_linux.sh -t`, then `ctest --test-dir build/tests`
|
||||
|
||||
Rebuild a single suite with `cmake --build build --config Release --target <suite>_tests`. Visual Studio and Xcode are multi-configuration generators, so `ctest` needs `-C` there; on Linux it does not.
|
||||
|
||||
## Where a test goes
|
||||
|
||||
- Pick the suite by the production code the test exercises, not by how the test is written.
|
||||
- A property of a class that holds with no `Print` involved belongs in `libslic3r`. Behavior that depends on print settings, or produces or consumes G-code or slicing state, belongs in `fff_print`.
|
||||
- One file per subsystem, named `test_<subsystem>.cpp`. It owns every test for that subsystem, whether the test reads in-memory state or generated output.
|
||||
- When you add a file, list it in that suite's `CMakeLists.txt` in the same change.
|
||||
|
||||
## Use the existing helpers
|
||||
|
||||
Check these before writing your own setup or output-parsing code.
|
||||
|
||||
- `tests/test_utils.hpp` is shared by every suite. `load_model()` loads a mesh from `tests/data/`, and `ScopedTemporaryFile` gives a temp path that removes itself.
|
||||
- `fff_print/test_helpers.hpp` builds and slices a `Print` and parses the emitted G-code. Read it before writing an fff_print test rather than assembling a `Print` by hand.
|
||||
- The other suites have their own: `sla_print/sla_test_utils.hpp`, `libnest2d/libnest2d_test_utils.hpp`, `slic3rutils/plugin_test_utils.hpp`, `filament_group/fg_test_utils.hpp`. `libslic3r` has none and uses the shared header.
|
||||
- Test data lives in `tests/data/` and is reached through the `TEST_DATA_DIR` define. Wrap it in `std::string(...)` before joining a path onto it.
|
||||
|
||||
## Writing the test
|
||||
|
||||
- Name the test case as a plain behavioral sentence in the present tense. No `Subsystem:` prefix.
|
||||
- Tag it with the subsystem it covers, matching the file, in PascalCase. That tag is what people filter on, so every test needs one.
|
||||
- Add further tags where they help: a narrower one to slice a large file (`[Rotcalip]`, `[Placer]`), a shared one for something spanning files (`[Python]`, `[H2C]`, `[Regression]`), or `[NotWorking]` / `[.]` to disable or hide a test. Say why in a comment if you disable or hide.
|
||||
- Prefer a flat `TEST_CASE` per behavior, with `GENERATE` for parameterized cases. Reserve `SCENARIO` / `GIVEN` / `WHEN` / `THEN` for genuine shared setup that branches into a few close variations.
|
||||
- Set the config keys your test depends on, and derive the expected values from what you set. A 20mm cube sliced at `layer_height` 2 is 10 layers, and the test should state both parts. If a number in your assertion comes from a key you never set, the test is also testing that default.
|
||||
- Assert the defining property, not an incidental value. "Skirt present" or "at least 2 brim loops" survives a refactor; exact coordinates and byte counts do not.
|
||||
- Name a regression test for the behavior it protects, never for an issue or PR number.
|
||||
- When asserting on G-code, match the meaningful token such as `; skirt` rather than whole lines, whitespace or comment wording. Depend on ordering only when ordering is the contract.
|
||||
|
||||
## Catch2 rules that cause real breakage
|
||||
|
||||
- Never reuse a `SECTION` name inside a loop. Use `DYNAMIC_SECTION` so each iteration is unique.
|
||||
- Never assert from a spawned thread. Catch2 assertions are not thread-safe. Collect results in the thread and assert on the main thread.
|
||||
- Never combine conditions with `&&` or `||` inside one assertion. Split them so Catch2 can print both operands on failure.
|
||||
- Compare floats with `WithinAbs` or `WithinRel`, never `==`. Prefer these over `Approx` in new tests.
|
||||
- Keep tests self-contained: no shared state, green under `--order rand`.
|
||||
369
tests/CATCH2.md
Normal file
369
tests/CATCH2.md
Normal file
@@ -0,0 +1,369 @@
|
||||
# Catch2 reference
|
||||
|
||||
How to write and structure test code with Catch2 in OrcaSlicer. For where a test belongs, how to name and tag it, and how to build and run the suites, see [AGENTS.md](AGENTS.md).
|
||||
|
||||
OrcaSlicer uses **Catch2 v3.11.0**, vendored in `tests/catch2/`. Include it with the single-header convenience include:
|
||||
|
||||
```cpp
|
||||
#include <catch2/catch_all.hpp>
|
||||
```
|
||||
|
||||
## Critical rules
|
||||
|
||||
These three mistakes produce undefined behavior, crashes, or useless failure output rather than a normal test failure. Avoid them everywhere.
|
||||
|
||||
### 1. Never reuse a section name inside a loop
|
||||
|
||||
A repeated `SECTION` name in a loop makes Catch2's section tracking behave unpredictably. Use `DYNAMIC_SECTION` so each iteration is unique.
|
||||
|
||||
```cpp
|
||||
// WRONG: same name every iteration
|
||||
for (int i = 0; i < 3; ++i)
|
||||
SECTION("Same name") { REQUIRE(i >= 0); }
|
||||
|
||||
// CORRECT
|
||||
for (int i = 0; i < 3; ++i)
|
||||
DYNAMIC_SECTION("Section " << i) { REQUIRE(i >= 0); }
|
||||
```
|
||||
|
||||
### 2. Assertions are not thread-safe
|
||||
|
||||
Catch2 assertions are not thread-safe by default. A `REQUIRE`/`CHECK` from a spawned thread corrupts internal state or terminates the process. Collect results in the thread, assert on the main thread.
|
||||
|
||||
```cpp
|
||||
// WRONG
|
||||
std::thread t([&]{ REQUIRE(work() == expected); });
|
||||
|
||||
// CORRECT
|
||||
std::atomic<int> passed{0};
|
||||
std::thread t([&]{ if (work() == expected) passed++; });
|
||||
t.join();
|
||||
REQUIRE(passed == 1);
|
||||
```
|
||||
|
||||
> Catch2 v3.9.0+ has opt-in thread-safe assertions via `CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS`. OrcaSlicer does not enable that flag, so assertions remain non-thread-safe. See [Thread safety](#thread-safety) below for the full rule list.
|
||||
|
||||
### 3. Do not combine conditions with binary operators
|
||||
|
||||
Catch2 decomposes a single comparison to show both operands on failure. A `&&`/`||` inside one assertion collapses to `false` with no values. Split it.
|
||||
|
||||
```cpp
|
||||
REQUIRE(a > 0 && b < 10); // WRONG: prints "false"
|
||||
REQUIRE(a > 0); // CORRECT: each prints its operands
|
||||
REQUIRE(b < 10);
|
||||
```
|
||||
|
||||
## Test structure
|
||||
|
||||
```cpp
|
||||
#include <catch2/catch_all.hpp>
|
||||
#include "libslic3r/Point.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("Behavioral description", "[SubsystemTag]") {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Assertions
|
||||
|
||||
```cpp
|
||||
// Stop the test on failure
|
||||
REQUIRE(expression);
|
||||
REQUIRE_FALSE(expression);
|
||||
|
||||
// Continue the test after failure (report all failures in the case)
|
||||
CHECK(expression);
|
||||
CHECK_FALSE(expression);
|
||||
|
||||
// Record the result without failing (for assumptions that may be violated)
|
||||
CHECK_NOFAIL(expression);
|
||||
```
|
||||
|
||||
### Exceptions
|
||||
|
||||
```cpp
|
||||
REQUIRE_NOTHROW(function_call());
|
||||
REQUIRE_THROWS(risky_function());
|
||||
REQUIRE_THROWS_AS(function_call(), SpecificException);
|
||||
REQUIRE_THROWS_WITH(function_call(), "Expected error message");
|
||||
REQUIRE_THROWS_MATCHES(function_call(), SpecificException,
|
||||
Catch::Matchers::Message("contains this"));
|
||||
```
|
||||
|
||||
Prefer these over a hand-rolled `try`/`catch` with a bool flag.
|
||||
|
||||
## Matchers
|
||||
|
||||
```cpp
|
||||
#include <catch2/matchers/catch_matchers.hpp>
|
||||
|
||||
// String matchers
|
||||
using Catch::Matchers::StartsWith;
|
||||
using Catch::Matchers::EndsWith;
|
||||
using Catch::Matchers::ContainsSubstring; // v2's "Contains" no longer exists
|
||||
using Catch::Matchers::Equals;
|
||||
using Catch::Matchers::Matches; // regex
|
||||
|
||||
REQUIRE_THAT(result, StartsWith("Expected prefix"));
|
||||
REQUIRE_THAT(result, ContainsSubstring("middle part"));
|
||||
REQUIRE_THAT(result, Matches(".*pattern.*"));
|
||||
|
||||
// Float matchers - always prefer these over Approx
|
||||
using Catch::Matchers::WithinAbs;
|
||||
using Catch::Matchers::WithinRel;
|
||||
using Catch::Matchers::WithinULP;
|
||||
|
||||
REQUIRE_THAT(v, WithinAbs(expected, 0.001));
|
||||
REQUIRE_THAT(v, WithinRel(expected, 0.01));
|
||||
REQUIRE_THAT(v, WithinULP(expected, 4));
|
||||
|
||||
// Combine: relative OR absolute (useful when the value can be near zero)
|
||||
REQUIRE_THAT(v, WithinRel(expected, 0.001) || WithinAbs(0.0, 0.000001));
|
||||
```
|
||||
|
||||
## Sections
|
||||
|
||||
Each `SECTION` re-runs the enclosing `TEST_CASE` body from the top, so setup declared before the sections is fresh for each one.
|
||||
|
||||
```cpp
|
||||
TEST_CASE("Complex feature", "[Feature]") {
|
||||
SomeObject obj; // rebuilt for every section
|
||||
|
||||
SECTION("First scenario") { REQUIRE(obj.method1() == expected_value); }
|
||||
SECTION("Second scenario") { REQUIRE(obj.method2() == other_expected); }
|
||||
}
|
||||
```
|
||||
|
||||
## BDD-style tests
|
||||
|
||||
`SCENARIO` / `GIVEN` / `WHEN` / `THEN` are aliases for `TEST_CASE` and `SECTION` with prefixed names. New tests should prefer a flat `TEST_CASE`; reserve BDD for genuine shared setup that branches into closely related variations (see the test-design guidance in [AGENTS.md](AGENTS.md)).
|
||||
|
||||
```cpp
|
||||
SCENARIO("User performs an operation", "[UserStory]") {
|
||||
GIVEN("A setup condition") {
|
||||
GCodeWriter writer;
|
||||
WHEN("The user acts") {
|
||||
auto result = writer.some_operation();
|
||||
THEN("The outcome holds") {
|
||||
REQUIRE(result.size() > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Generators
|
||||
|
||||
```cpp
|
||||
// Value list
|
||||
auto v = GENERATE(1, 3, 5, 7, 11, 13);
|
||||
|
||||
// Range
|
||||
auto i = GENERATE(range(1, 10)); // 1..9
|
||||
|
||||
// From a variable (use GENERATE_REF / GENERATE_COPY for captured references)
|
||||
std::vector<int> values = {1, 2, 3, 4, 5};
|
||||
auto x = GENERATE_REF(from_range(values));
|
||||
|
||||
// Random
|
||||
auto r = GENERATE(take(100, random(-1000, 1000)));
|
||||
```
|
||||
|
||||
## Fixtures
|
||||
|
||||
```cpp
|
||||
class GeometryFixture {
|
||||
public:
|
||||
Point origin{0, 0};
|
||||
Point unit_x{1, 0};
|
||||
};
|
||||
|
||||
TEST_CASE_METHOD(GeometryFixture, "Point operations", "[Geometry]") {
|
||||
REQUIRE(origin.distance_to(unit_x) == 1.0);
|
||||
}
|
||||
```
|
||||
|
||||
Persistent (`TEST_CASE_PERSISTENT_FIXTURE`, one instance for the whole case) and type-parameterized (`TEMPLATE_TEST_CASE_METHOD`) variants also exist; neither is used in the suite today.
|
||||
|
||||
## Advanced features
|
||||
|
||||
### Logging and control
|
||||
|
||||
```cpp
|
||||
INFO("Persists until end of scope");
|
||||
UNSCOPED_INFO("Survives beyond its scope"); // v2.7.0+
|
||||
CAPTURE(some_variable, another_var); // logs names and values
|
||||
|
||||
WARN("Warns without failing");
|
||||
SKIP("Reason"); // marks the test skipped (v3.3.0+)
|
||||
FAIL("Stops the test");
|
||||
SUCCEED("Explicit success marker");
|
||||
```
|
||||
|
||||
### Other macros
|
||||
|
||||
Available but currently unused in the suite; see the upstream docs for details.
|
||||
|
||||
- **Compile-time asserts**: `STATIC_REQUIRE` / `STATIC_CHECK` (v3.0.1+) check type traits at compile time.
|
||||
- **Conditional blocks**: `CHECKED_IF` / `CHECKED_ELSE` record a branch condition without counting it as a failure.
|
||||
- **Benchmarking** (v2.9.0+): `BENCHMARK("name") { return work(); };`, or `BENCHMARK_ADVANCED` when setup must be excluded from the measurement.
|
||||
|
||||
## Usage patterns in OrcaSlicer
|
||||
|
||||
Concrete shapes for exercising the codebase's own types. Test data is reached through the `TEST_DATA_DIR` define; always wrap it in `std::string(...)` before concatenating a path.
|
||||
|
||||
```cpp
|
||||
// Geometry, with epsilon tolerance
|
||||
TEST_CASE("Line operations", "[Geometry]") {
|
||||
Line line{{100000, 0}, {0, 0}};
|
||||
Line rotated(line);
|
||||
rotated.rotate(0.9 * EPSILON, {0, 0});
|
||||
REQUIRE(line.parallel_to(rotated));
|
||||
}
|
||||
|
||||
// Config from an ini
|
||||
TEST_CASE("Config loading", "[Config]") {
|
||||
DynamicPrintConfig config;
|
||||
REQUIRE_NOTHROW(config.load_from_ini(std::string(TEST_DATA_DIR) + "/test_config/sample.ini",
|
||||
ForwardCompatibilitySubstitutionRule::Disable));
|
||||
REQUIRE(config.has("layer_height"));
|
||||
}
|
||||
|
||||
// File I/O
|
||||
TEST_CASE("STL file parsing", "[FileFormat]") {
|
||||
TriangleMesh mesh;
|
||||
REQUIRE_NOTHROW(mesh.ReadSTLFile((std::string(TEST_DATA_DIR) + "/test_stl/20mmbox.stl").c_str()));
|
||||
REQUIRE_FALSE(mesh.empty());
|
||||
REQUIRE(mesh.volume() > 0);
|
||||
}
|
||||
|
||||
// G-code emission, matched by token (see test_gcodewriter.cpp)
|
||||
TEST_CASE("z_hop lifts the nozzle", "[GCodeWriter]") {
|
||||
GCodeWriter writer;
|
||||
writer.set_extruders({0});
|
||||
writer.set_extruder(0);
|
||||
writer.travel_to_z(10.0);
|
||||
writer.config.z_hop.values = {1.0};
|
||||
REQUIRE_THAT(writer.eager_lift(LiftType::NormalLift), Catch::Matchers::ContainsSubstring("Z11"));
|
||||
}
|
||||
```
|
||||
|
||||
### Custom string conversions
|
||||
|
||||
Give Catch2 a way to print a custom type on failure. The usual case is an `operator<<` overload:
|
||||
|
||||
```cpp
|
||||
std::ostream& operator<<(std::ostream& os, const Point& p) {
|
||||
return os << "Point(" << p.x << ", " << p.y << ")";
|
||||
}
|
||||
```
|
||||
|
||||
When you cannot add `operator<<`, specialize `Catch::StringMaker<T>`. Enums can be registered with `CATCH_REGISTER_ENUM` (at global scope) and exceptions translated with `CATCH_TRANSLATE_EXCEPTION`; see the upstream docs for those.
|
||||
|
||||
## Command line
|
||||
|
||||
[AGENTS.md](AGENTS.md) covers the everyday commands (CTest, per-suite runs, tag filtering as CTest labels). The flags below are Catch2's own, available when you run a suite executable directly.
|
||||
|
||||
```bash
|
||||
# Filtering
|
||||
suite_tests "[Geometry]" # by tag
|
||||
suite_tests "*geometry*" # by name pattern
|
||||
suite_tests "~[Performance]" # exclude a tag
|
||||
suite_tests "[Geometry][Config],[Algorithm]" # (Geometry AND Config) OR Algorithm
|
||||
|
||||
# Discovery
|
||||
suite_tests --list-tests
|
||||
suite_tests --list-tags
|
||||
suite_tests --list-reporters
|
||||
|
||||
# Debugging a failure
|
||||
suite_tests --break # break into the debugger on failure
|
||||
suite_tests --success # show passing assertions too
|
||||
suite_tests --durations yes # per-test timing
|
||||
suite_tests --abort # stop at the first failure
|
||||
```
|
||||
|
||||
### Ordering and sharding
|
||||
|
||||
Run in random order so tests stay independent. For parallel shards, all shards must share one seed.
|
||||
|
||||
```bash
|
||||
suite_tests --order rand --warn NoAssertions
|
||||
|
||||
suite_tests --order rand --shard-index 0 --shard-count 4 --rng-seed 0xBEEF
|
||||
suite_tests --order rand --shard-index 1 --shard-count 4 --rng-seed 0xBEEF
|
||||
# ...one invocation per shard index
|
||||
```
|
||||
|
||||
### Reporters
|
||||
|
||||
```bash
|
||||
suite_tests --reporter console # default, human-readable
|
||||
suite_tests --reporter compact
|
||||
suite_tests --reporter xml # Catch2 XML
|
||||
suite_tests --reporter junit # JUnit XML (CI)
|
||||
suite_tests --reporter tap
|
||||
suite_tests --reporter console --reporter junit::out=results.xml # multiple at once
|
||||
```
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
### Floating-point comparison
|
||||
|
||||
Compare floats with the float matchers, never with `==`. New tests should prefer the `Within*` matchers over `Approx`. Many existing tests still use `Approx`, which works but is:
|
||||
|
||||
- **Asymmetric**: `Approx(10).epsilon(0.1) != 11.1` yet `Approx(11.1).epsilon(0.1) == 10`.
|
||||
- **Double-only**: all math is done in `double`, which misbehaves for `float` inputs.
|
||||
- **Relative by default**: `Approx(0) == X` holds only for `X == 0`.
|
||||
|
||||
Use `WithinAbs` near zero, `WithinRel` across magnitudes, `WithinULP` for the tightest check, or combine them. `Catch::StringMaker<double>::precision = 15;` widens printed precision.
|
||||
|
||||
### Exception testing
|
||||
|
||||
Use `REQUIRE_THROWS` / `REQUIRE_THROWS_AS` rather than a `try`/`catch` with a bool flag.
|
||||
|
||||
### Thread safety
|
||||
|
||||
Assertions are not thread-safe (see [Critical rule 2](#2-assertions-are-not-thread-safe)). The full list of macros that must stay on the main thread:
|
||||
|
||||
- **`REQUIRE` family**: throws in a spawned thread with no handler, terminating the process.
|
||||
- **`CHECK` family**: can corrupt internal state.
|
||||
- **`SKIP`, `FAIL`, `SUCCEED`**: unsafe even with v3's opt-in thread-safe assertions.
|
||||
- **Message macros** (`INFO`, `CAPTURE`, `WARN`): unsafe.
|
||||
- **`STATIC_REQUIRE` / `STATIC_CHECK`**: unsafe (rely on runtime registration).
|
||||
|
||||
### Path handling
|
||||
|
||||
Wrap `TEST_DATA_DIR` in `std::string(...)` before concatenating, or use `boost::filesystem`:
|
||||
|
||||
```cpp
|
||||
std::string path = std::string(TEST_DATA_DIR) + "/model.obj";
|
||||
```
|
||||
|
||||
### Memory
|
||||
|
||||
Prefer RAII and smart pointers so a failing assertion cleans up automatically.
|
||||
|
||||
## Compilation and performance flags
|
||||
|
||||
```cpp
|
||||
#define CATCH_CONFIG_FAST_COMPILE // ~20% faster compile, disables some features
|
||||
#define CATCH_CONFIG_DISABLE_STRINGIFICATION // works around the VS2017 raw-string bug
|
||||
#define CATCH_CONFIG_WINDOWS_CRTDBG // memory-leak detection (whole build)
|
||||
```
|
||||
|
||||
The test build already defines `CATCH_CONFIG_FAST_COMPILE` (via `test_common` in `tests/CMakeLists.txt`).
|
||||
|
||||
## Platform-specific workarounds
|
||||
|
||||
- **MinGW/Cygwin** slow linking: build with `-fuse-ld=lld`.
|
||||
- **Visual Studio 2017** raw-string-literal bug: define `CATCH_CONFIG_DISABLE_STRINGIFICATION` (disables expression stringification).
|
||||
- **Visual Studio 2022** spaceship operator: `REQUIRE((a <=> b) == 0)` may not compile; use clang-cl or avoid `<=>` in assertions.
|
||||
|
||||
## Catch2 v3 notes
|
||||
|
||||
Available on v3.11.0: `SKIP()` (v3.3.0+), opt-in thread-safe assertions (v3.9.0+, not enabled here), built-in `BENCHMARK`, multiple simultaneous reporters (v3.0.1+), `STATIC_CHECK` (v3.0.1+), built-in sharding (`--shard-*`).
|
||||
|
||||
Two behavior notes: the string matcher is `ContainsSubstring` (v2's `Contains` is gone), and a section is re-run when a later sibling section fails (unchanged from v2).
|
||||
965
tests/CLAUDE.md
965
tests/CLAUDE.md
@@ -1,964 +1 @@
|
||||
# CLAUDE.md - Testing Guide for OrcaSlicer
|
||||
|
||||
This guide provides comprehensive instructions for Claude Code when writing, maintaining, and understanding tests in the OrcaSlicer codebase.
|
||||
|
||||
> **Adding or organizing `fff_print` tests?** See
|
||||
> [fff_print/README.md](fff_print/README.md) for where a test belongs and how to
|
||||
> name it. This guide covers Catch2 mechanics; that README is the suite's
|
||||
> organizing contract.
|
||||
|
||||
## ⚠️ CRITICAL RULES - MUST FOLLOW
|
||||
|
||||
### 1. **SECTIONS IN LOOPS - NEVER REUSE NAMES**
|
||||
❌ **WRONG**: Will cause unpredictable behavior
|
||||
```cpp
|
||||
TEST_CASE("Bad loop sections") {
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
SECTION("Same name") { // WRONG! Same name used multiple times
|
||||
REQUIRE(i >= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
✅ **CORRECT**: Use DYNAMIC_SECTION or incorporate counter
|
||||
```cpp
|
||||
TEST_CASE("Good loop sections") {
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
DYNAMIC_SECTION("Section " << i) { // Unique name per iteration
|
||||
REQUIRE(i >= 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. **THREAD SAFETY - ASSERTIONS ARE NOT THREAD-SAFE**
|
||||
❌ **WRONG**: Will cause undefined behavior or crashes
|
||||
```cpp
|
||||
TEST_CASE("Multi-threaded test") {
|
||||
std::vector<std::thread> threads;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
threads.emplace_back([]() {
|
||||
REQUIRE(some_calculation() == expected); // NOT THREAD-SAFE!
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
✅ **CORRECT**: Synchronize results, test on main thread
|
||||
```cpp
|
||||
TEST_CASE("Multi-threaded test") {
|
||||
std::vector<std::thread> threads;
|
||||
std::atomic<int> passed{0};
|
||||
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
threads.emplace_back([&passed]() {
|
||||
if (some_calculation() == expected) {
|
||||
passed++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (auto& t : threads) t.join();
|
||||
REQUIRE(passed == 4); // Test results on main thread
|
||||
}
|
||||
```
|
||||
|
||||
### 3. **EXPRESSION DECOMPOSITION - AVOID BINARY OPERATORS**
|
||||
❌ **WRONG**: Cannot decompose properly
|
||||
```cpp
|
||||
REQUIRE(a > 0 && b < 10); // Shows "false" on failure, not individual values
|
||||
```
|
||||
|
||||
✅ **CORRECT**: Split into separate assertions
|
||||
```cpp
|
||||
REQUIRE(a > 0);
|
||||
REQUIRE(b < 10); // Each shows individual values on failure
|
||||
```
|
||||
|
||||
### 4. **FLOATING POINT - NEVER USE APPROX**
|
||||
❌ **WRONG**: Approx is deprecated and asymmetric
|
||||
```cpp
|
||||
REQUIRE(calculated_value == Catch::Approx(expected)); // Deprecated!
|
||||
```
|
||||
|
||||
✅ **CORRECT**: Use floating point matchers
|
||||
```cpp
|
||||
REQUIRE_THAT(calculated_value, WithinAbs(expected, 0.001));
|
||||
REQUIRE_THAT(calculated_value, WithinRel(expected, 0.01)); // 1% tolerance
|
||||
REQUIRE_THAT(calculated_value, WithinULP(expected, 4)); // 4 ULPs apart
|
||||
```
|
||||
|
||||
### 5. **TEST ORDERING - ALWAYS USE RANDOM ORDER**
|
||||
✅ **REQUIRED**: For CI/CD and development
|
||||
```bash
|
||||
# Essential flags for running tests
|
||||
./tests --order rand --warn NoAssertions
|
||||
|
||||
# For test sharding (parallel execution), share random seed
|
||||
./tests --order rand --shard-index 0 --shard-count 3 --rng-seed 0xBEEF
|
||||
./tests --order rand --shard-index 1 --shard-count 3 --rng-seed 0xBEEF
|
||||
./tests --order rand --shard-index 2 --shard-count 3 --rng-seed 0xBEEF
|
||||
```
|
||||
|
||||
## Overview of OrcaSlicer's Testing Framework
|
||||
|
||||
OrcaSlicer uses **Catch2 v3** (currently v3.11.0, vendored in `tests/catch2/`) as its primary testing framework. The test suite is organized into several modules that mirror the project's architectural components:
|
||||
|
||||
> **Note**: Test files include the framework via `#include <catch2/catch_all.hpp>` (the v3 single-header convenience include). All v3 features described in this guide are available.
|
||||
|
||||
### Test Structure
|
||||
```
|
||||
tests/
|
||||
├── CMakeLists.txt # Main test configuration
|
||||
├── catch_main.hpp # Custom test reporter
|
||||
├── libslic3r/ # Core library tests (21 test files)
|
||||
├── fff_print/ # FFF printing tests (12 test files)
|
||||
├── sla_print/ # SLA printing tests (4 test files)
|
||||
├── libnest2d/ # 2D nesting tests
|
||||
├── slic3rutils/ # Utility tests
|
||||
├── data/ # Test data files and meshes
|
||||
└── catch2/ # Catch2 framework files
|
||||
```
|
||||
|
||||
### Build Integration
|
||||
- Tests are built using CMake with `catch_discover_tests()` integration
|
||||
- Each test module creates a separate executable (e.g., `libslic3r_tests`, `fff_print_tests`)
|
||||
- Test data directory is available via `TEST_DATA_DIR` preprocessor definition
|
||||
- Custom verbose console reporter provides detailed test output
|
||||
|
||||
## Test Suite Organization
|
||||
|
||||
### libslic3r Tests
|
||||
Core slicing engine tests covering:
|
||||
- **Geometry operations**: Points, polygons, lines, Voronoi diagrams
|
||||
- **File formats**: STL, 3MF, AMF parsing and validation
|
||||
- **Algorithms**: Clipper operations, mesh boolean operations, optimization
|
||||
- **Configuration**: Print settings validation and parsing
|
||||
- **Utilities**: String processing, time utilities, data structures
|
||||
|
||||
### fff_print Tests
|
||||
Fused Filament Fabrication specific tests:
|
||||
- **G-code generation**: Writer functionality, cooling, lift/unlift
|
||||
- **Slicing algorithms**: Layer generation, infill patterns
|
||||
- **Print mechanics**: Flow calculations, extrusion, support material
|
||||
- **Model processing**: Print objects, skirt/brim generation
|
||||
|
||||
### sla_print Tests
|
||||
Stereolithography specific tests:
|
||||
- **SLA print processing**: Layer curing, support generation
|
||||
- **Raycast operations**: Light path calculations
|
||||
- **Test utilities**: SLA-specific helper functions
|
||||
|
||||
## Writing New Tests - Best Practices
|
||||
|
||||
### File Organization
|
||||
1. **Naming Convention**: `test_<feature>.cpp` (e.g., `test_geometry.cpp`)
|
||||
2. **Header Structure**: Include `<catch2/catch_all.hpp>` first, then relevant headers
|
||||
3. **Namespace Usage**: Use `using namespace Slic3r;` for convenience
|
||||
4. **File Placement**: Add to appropriate test directory and update CMakeLists.txt
|
||||
|
||||
### Test Naming and Structure
|
||||
```cpp
|
||||
#include <catch2/catch_all.hpp>
|
||||
#include "libslic3r/Point.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("Feature description", "[category_tag]") {
|
||||
// Test implementation
|
||||
}
|
||||
```
|
||||
|
||||
### Tagging System
|
||||
Use descriptive tags for test categorization:
|
||||
- `[Geometry]` - Geometric operations and calculations
|
||||
- `[GCodeWriter]` - G-code generation functionality
|
||||
- `[Config]` - Configuration and settings tests
|
||||
- `[FileFormat]` - File I/O operations (STL, 3MF, etc.)
|
||||
- `[Algorithm]` - Core algorithms and processing
|
||||
- `[Performance]` - Performance benchmarks (if applicable)
|
||||
|
||||
## Catch2 Features Guide
|
||||
|
||||
### Basic Assertions
|
||||
```cpp
|
||||
// Primary assertions - stop test on failure
|
||||
REQUIRE(expression);
|
||||
REQUIRE_FALSE(expression);
|
||||
|
||||
// Continuing assertions - continue test after failure
|
||||
CHECK(expression);
|
||||
CHECK_FALSE(expression);
|
||||
|
||||
// Non-failing checks - record result but don't fail test
|
||||
CHECK_NOFAIL(expression); // Useful for assumptions that might be violated
|
||||
```
|
||||
|
||||
### Exception Testing
|
||||
```cpp
|
||||
// Verify no exception is thrown
|
||||
REQUIRE_NOTHROW(function_call());
|
||||
|
||||
// Verify any exception is thrown
|
||||
REQUIRE_THROWS(risky_function());
|
||||
|
||||
// Verify specific exception type
|
||||
REQUIRE_THROWS_AS(function_call(), SpecificException);
|
||||
|
||||
// Verify exception message
|
||||
REQUIRE_THROWS_WITH(function_call(), "Expected error message");
|
||||
|
||||
// Verify exception with matchers (for partial matching)
|
||||
REQUIRE_THROWS_MATCHES(function_call(), SpecificException,
|
||||
Catch::Matchers::Message("contains this"));
|
||||
```
|
||||
|
||||
### Complex Assertions with Matchers
|
||||
```cpp
|
||||
#include <catch2/matchers/catch_matchers.hpp>
|
||||
|
||||
// String matchers
|
||||
using Catch::Matchers::StartsWith;
|
||||
using Catch::Matchers::EndsWith;
|
||||
using Catch::Matchers::ContainsSubstring;
|
||||
using Catch::Matchers::Equals;
|
||||
using Catch::Matchers::Matches; // Regex matching
|
||||
|
||||
REQUIRE_THAT(result_string, StartsWith("Expected prefix"));
|
||||
REQUIRE_THAT(result_string, ContainsSubstring("middle part"));
|
||||
REQUIRE_THAT(result_string, Matches(".*pattern.*"));
|
||||
|
||||
// Floating point matchers - ALWAYS use these instead of Approx!
|
||||
using Catch::Matchers::WithinAbs;
|
||||
using Catch::Matchers::WithinRel;
|
||||
using Catch::Matchers::WithinULP;
|
||||
|
||||
REQUIRE_THAT(float_value, WithinAbs(expected, 0.001)); // Absolute tolerance
|
||||
REQUIRE_THAT(float_value, WithinRel(expected, 0.01)); // Relative tolerance (1%)
|
||||
REQUIRE_THAT(float_value, WithinULP(expected, 4)); // ULP difference (requires IEEE-754)
|
||||
|
||||
// Combining matchers
|
||||
REQUIRE_THAT(value, WithinRel(expected, 0.001) || WithinAbs(0.0, 0.000001));
|
||||
```
|
||||
|
||||
### Sections for Test Organization
|
||||
```cpp
|
||||
TEST_CASE("Complex feature testing", "[Feature]") {
|
||||
// Common setup code
|
||||
SomeObject obj;
|
||||
|
||||
SECTION("First scenario") {
|
||||
// Specific test case
|
||||
REQUIRE(obj.method1() == expected_value);
|
||||
}
|
||||
|
||||
SECTION("Second scenario") {
|
||||
// Another test case with same setup
|
||||
REQUIRE(obj.method2() == other_expected);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### BDD-Style Tests
|
||||
Use for complex scenarios and user story testing:
|
||||
|
||||
> **Note**: BDD macros are aliases for TEST_CASE and SECTION with prefixed names
|
||||
```cpp
|
||||
SCENARIO("User performs complex operation", "[UserStory]") {
|
||||
GIVEN("A specific setup condition") {
|
||||
GCodeWriter writer;
|
||||
// Setup code
|
||||
|
||||
WHEN("User performs action") {
|
||||
auto result = writer.some_operation();
|
||||
|
||||
THEN("Expected outcome occurs") {
|
||||
REQUIRE(result.size() > 0);
|
||||
|
||||
AND_WHEN("Follow-up action occurs") {
|
||||
auto next_result = writer.next_operation();
|
||||
|
||||
THEN("Final outcome is correct") {
|
||||
REQUIRE(next_result == expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Data Generators for Parameterized Tests
|
||||
```cpp
|
||||
TEST_CASE("Function works with various inputs", "[Algorithm]") {
|
||||
auto test_value = GENERATE(1, 3, 5, 7, 11, 13);
|
||||
|
||||
REQUIRE(is_odd(test_value));
|
||||
REQUIRE(test_value > 0);
|
||||
}
|
||||
|
||||
// Range-based generators
|
||||
TEST_CASE("Range testing", "[Algorithm]") {
|
||||
auto i = GENERATE(range(1, 10)); // 1 to 9
|
||||
REQUIRE(process_value(i) > i);
|
||||
}
|
||||
|
||||
// Using variables in generators (requires GENERATE_COPY or GENERATE_REF)
|
||||
TEST_CASE("Generator with variables", "[Algorithm]") {
|
||||
std::vector<int> values = {1, 2, 3, 4, 5};
|
||||
auto test_value = GENERATE_REF(from_range(values)); // Use GENERATE_REF for references
|
||||
|
||||
REQUIRE(test_value > 0);
|
||||
}
|
||||
|
||||
// Custom generators
|
||||
TEST_CASE("Random values", "[Algorithm]") {
|
||||
auto random_int = GENERATE(take(100, random(-1000, 1000))); // 100 random values
|
||||
REQUIRE(process_random_value(random_int));
|
||||
}
|
||||
```
|
||||
|
||||
### Test Fixtures
|
||||
```cpp
|
||||
class GeometryFixture {
|
||||
public:
|
||||
Point origin{0, 0};
|
||||
Point unit_x{1, 0};
|
||||
Point unit_y{0, 1};
|
||||
|
||||
mutable double tolerance = EPSILON; // Use mutable for data that might change
|
||||
};
|
||||
|
||||
// Standard fixture - new instance per test run
|
||||
TEST_CASE_METHOD(GeometryFixture, "Point operations", "[Geometry]") {
|
||||
REQUIRE(origin.distance_to(unit_x) == 1.0);
|
||||
}
|
||||
|
||||
// Persistent fixture - single instance for entire test case (v3.2.0+)
|
||||
TEST_CASE_PERSISTENT_FIXTURE(GeometryFixture, "Persistent operations", "[Geometry]") {
|
||||
static int call_count = 0;
|
||||
++call_count;
|
||||
INFO("This fixture persists across sections, call: " << call_count);
|
||||
|
||||
SECTION("First section") {
|
||||
REQUIRE(origin.distance_to(unit_x) == 1.0);
|
||||
}
|
||||
|
||||
SECTION("Second section") {
|
||||
REQUIRE(origin.distance_to(unit_y) == 1.0);
|
||||
// call_count will be 2 here with persistent fixture
|
||||
}
|
||||
}
|
||||
|
||||
// Template fixtures for type-parameterized tests
|
||||
template<typename T>
|
||||
class NumericFixture {
|
||||
public:
|
||||
T zero = T{0};
|
||||
T one = T{1};
|
||||
};
|
||||
|
||||
TEMPLATE_TEST_CASE_METHOD(NumericFixture, "Numeric operations", "[Template]", int, float, double) {
|
||||
REQUIRE(TestType{} == this->zero);
|
||||
REQUIRE(TestType{1} == this->one);
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Testing Features
|
||||
|
||||
#### Logging and Information Macros
|
||||
```cpp
|
||||
TEST_CASE("Advanced logging", "[Logging]") {
|
||||
INFO("This info persists until end of scope");
|
||||
|
||||
SECTION("Section A") {
|
||||
INFO("Section A specific info");
|
||||
CAPTURE(some_variable, another_var); // Captures variable names and values
|
||||
CHECK(some_condition);
|
||||
}
|
||||
|
||||
SECTION("Section B") {
|
||||
UNSCOPED_INFO("This survives beyond its scope"); // v2.7.0+
|
||||
CHECK(other_condition);
|
||||
}
|
||||
}
|
||||
|
||||
// Warning and explicit control
|
||||
TEST_CASE("Explicit test control", "[Control]") {
|
||||
WARN("This warns but doesn't fail the test");
|
||||
|
||||
if (precondition_not_met) {
|
||||
SKIP("Reason"); // Marks the test as skipped (v3.3.0+, available)
|
||||
return;
|
||||
}
|
||||
|
||||
if (critical_failure) {
|
||||
FAIL("Critical condition failed"); // Fails and stops test
|
||||
}
|
||||
|
||||
SUCCEED("Reached successful completion"); // Explicit success marker
|
||||
}
|
||||
```
|
||||
|
||||
#### Static Assertions (Compile-time Testing)
|
||||
```cpp
|
||||
TEST_CASE("Compile-time checks", "[Static]") {
|
||||
STATIC_REQUIRE(sizeof(int) >= 4); // Checked at compile time
|
||||
STATIC_REQUIRE_FALSE(std::is_void_v<int>);
|
||||
|
||||
// For traits and template metaprogramming
|
||||
STATIC_CHECK(std::is_trivially_copyable_v<Point>); // v3.0.1+
|
||||
}
|
||||
```
|
||||
|
||||
#### Conditional Testing
|
||||
```cpp
|
||||
TEST_CASE("Conditional blocks", "[Conditional]") {
|
||||
int value = get_test_value();
|
||||
|
||||
// These record the expression but don't count as test failures (v3.0.1+)
|
||||
CHECKED_IF(value > 0) {
|
||||
// This block runs if value > 0
|
||||
REQUIRE(value <= 100);
|
||||
} CHECKED_ELSE(value > 0) {
|
||||
// This block runs if value <= 0
|
||||
REQUIRE(value >= -100);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Benchmarking (v2.9.0+)
|
||||
```cpp
|
||||
TEST_CASE("Performance testing", "[Benchmark]") {
|
||||
// Simple benchmarking
|
||||
BENCHMARK("Algorithm performance") {
|
||||
return expensive_algorithm();
|
||||
};
|
||||
|
||||
// Advanced benchmarking with setup
|
||||
BENCHMARK_ADVANCED("Advanced benchmark")(Catch::Benchmark::Chronometer meter) {
|
||||
std::vector<int> data = setup_test_data(); // Setup not measured
|
||||
|
||||
meter.measure([&] {
|
||||
return process_data(data); // Only this is measured
|
||||
});
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## OrcaSlicer-Specific Testing Patterns
|
||||
|
||||
### Geometry Testing
|
||||
```cpp
|
||||
TEST_CASE("Line operations", "[Geometry]") {
|
||||
Line line{{100000, 0}, {0, 0}};
|
||||
Line parallel{{200000, 0}, {0, 0}};
|
||||
|
||||
REQUIRE(line.parallel_to(line));
|
||||
REQUIRE(line.parallel_to(parallel));
|
||||
|
||||
// Test with epsilon tolerance
|
||||
Line rotated(parallel);
|
||||
rotated.rotate(0.9 * EPSILON, {0, 0});
|
||||
REQUIRE(line.parallel_to(rotated));
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Testing
|
||||
```cpp
|
||||
TEST_CASE("Config loading", "[Config]") {
|
||||
DynamicPrintConfig config;
|
||||
std::string config_path = std::string(TEST_DATA_DIR) + "/test_config/sample.ini";
|
||||
|
||||
REQUIRE_NOTHROW(config.load_from_ini(config_path));
|
||||
REQUIRE(config.has("layer_height"));
|
||||
}
|
||||
```
|
||||
|
||||
### File I/O Testing
|
||||
```cpp
|
||||
TEST_CASE("STL file parsing", "[FileFormat]") {
|
||||
std::string stl_path = std::string(TEST_DATA_DIR) + "/test_stl/20mmbox.stl";
|
||||
|
||||
TriangleMesh mesh;
|
||||
REQUIRE_NOTHROW(mesh.ReadSTLFile(stl_path.c_str()));
|
||||
REQUIRE(!mesh.empty());
|
||||
REQUIRE(mesh.volume() > 0);
|
||||
}
|
||||
```
|
||||
|
||||
### G-code Generation Testing
|
||||
```cpp
|
||||
TEST_CASE("G-code writer functionality", "[GCodeWriter]") {
|
||||
GCodeWriter writer;
|
||||
|
||||
// Load test configuration
|
||||
std::string config_path = std::string(TEST_DATA_DIR) + "/fff_print_tests/test_config.ini";
|
||||
writer.config.load(config_path, ForwardCompatibilitySubstitutionRule::Disable);
|
||||
|
||||
// Test specific G-code generation
|
||||
std::string result = writer.lift();
|
||||
REQUIRE(!result.empty());
|
||||
REQUIRE_THAT(result, Catch::Matchers::ContainsSubstring("G1"));
|
||||
}
|
||||
```
|
||||
|
||||
### Performance Testing Patterns
|
||||
```cpp
|
||||
TEST_CASE("Algorithm performance", "[Performance][Algorithm]") {
|
||||
// Large test data
|
||||
std::vector<Point> points = generate_large_point_set(10000);
|
||||
|
||||
// Time the operation (manual timing example; the BENCHMARK macro is also available)
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
auto result = convex_hull(points);
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
|
||||
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
|
||||
|
||||
REQUIRE(result.size() > 0);
|
||||
REQUIRE(duration.count() < 1000); // Should complete in < 1 second
|
||||
}
|
||||
```
|
||||
|
||||
### Custom String Conversions
|
||||
|
||||
#### For Custom Types
|
||||
```cpp
|
||||
// Method 1: operator<< overload (preferred)
|
||||
std::ostream& operator<<(std::ostream& os, const Point& point) {
|
||||
os << "Point(" << point.x << ", " << point.y << ")";
|
||||
return os;
|
||||
}
|
||||
|
||||
// Method 2: StringMaker specialization
|
||||
namespace Catch {
|
||||
template<>
|
||||
struct StringMaker<MyCustomType> {
|
||||
static std::string convert(const MyCustomType& value) {
|
||||
return "MyCustomType{" + std::to_string(value.data) + "}";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Method 3: Enum registration (v2.8.0+)
|
||||
enum class Status { Ready, Processing, Complete, Error };
|
||||
|
||||
// Must be at global scope!
|
||||
CATCH_REGISTER_ENUM(Status, Status::Ready, Status::Processing, Status::Complete, Status::Error);
|
||||
|
||||
// Method 4: Exception translation
|
||||
CATCH_TRANSLATE_EXCEPTION(MyCustomException const& ex) {
|
||||
return "MyCustomException: " + std::string(ex.what());
|
||||
}
|
||||
|
||||
// Method 5: Disable range iteration for problematic types
|
||||
namespace Catch {
|
||||
template<>
|
||||
struct is_range<ProblematicType> {
|
||||
static const bool value = false;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Running and Debugging Tests
|
||||
|
||||
### Building Tests
|
||||
```bash
|
||||
# Build all tests
|
||||
cd build && make
|
||||
|
||||
# Build specific test suite
|
||||
cd build && make libslic3r_tests
|
||||
|
||||
# Build and run tests
|
||||
cd build && make && ctest
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
#### Essential Test Execution Patterns
|
||||
```bash
|
||||
# REQUIRED: Random order with assertion warnings (best practice)
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --warn NoAssertions
|
||||
|
||||
# Run all tests with verbose output via CTest
|
||||
cd build && ctest --output-on-failure
|
||||
|
||||
# Run specific test suite with best practices
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --warn NoAssertions
|
||||
|
||||
# Filter tests with specific tags
|
||||
cd build && ./tests/libslic3r/libslic3r_tests "[Geometry]" --order rand
|
||||
|
||||
# Filter by test name patterns
|
||||
cd build && ./tests/libslic3r/libslic3r_tests "*geometry*" --order rand
|
||||
|
||||
# Exclude tests (negation)
|
||||
cd build && ./tests/libslic3r/libslic3r_tests "~[Performance]" --order rand
|
||||
|
||||
# Combine filters: (Geometry AND Config) OR Algorithm
|
||||
cd build && ./tests/libslic3r/libslic3r_tests "[Geometry][Config],[Algorithm]" --order rand
|
||||
|
||||
# List available tests, tags, and reporters
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --list-tests
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --list-tags
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --list-reporters
|
||||
|
||||
# Debug failing tests
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --break # Break into debugger on failure
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --success # Show passing tests too
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --durations yes # Show timing info
|
||||
|
||||
# Abort on first failure
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --abort
|
||||
|
||||
# Test sharding for parallel execution (MUST share random seed)
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --shard-index 0 --shard-count 4 --rng-seed 0xBEEF &
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --shard-index 1 --shard-count 4 --rng-seed 0xBEEF &
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --shard-index 2 --shard-count 4 --rng-seed 0xBEEF &
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --order rand --shard-index 3 --shard-count 4 --rng-seed 0xBEEF &
|
||||
wait # Wait for all to complete
|
||||
```
|
||||
|
||||
#### Reporter Options for CI Integration
|
||||
```bash
|
||||
# Different output formats for CI systems
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter console # Default human-readable
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter compact # Minimal output
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter xml # Catch2 XML format
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter junit # JUnit XML (widely supported)
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter tap # Test Anything Protocol
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter teamcity # TeamCity integration
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter sonarqube # SonarQube integration
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter automake # Automake integration
|
||||
|
||||
# Multiple reporters simultaneously (if supported)
|
||||
cd build && ./tests/libslic3r/libslic3r_tests --reporter console --reporter junit::out=results.xml
|
||||
```
|
||||
|
||||
### Test Output Control
|
||||
The custom `VerboseConsoleReporter` provides enhanced output:
|
||||
- Test case start/end notifications with timing
|
||||
- Section execution tracking
|
||||
- Color-coded success/failure indicators
|
||||
- Duration reporting for performance analysis
|
||||
|
||||
## Test Data Management
|
||||
|
||||
### Using TEST_DATA_DIR
|
||||
All test data is accessible via the `TEST_DATA_DIR` preprocessor definition:
|
||||
|
||||
```cpp
|
||||
std::string mesh_path = std::string(TEST_DATA_DIR) + "/20mm_cube.obj";
|
||||
std::string config_path = std::string(TEST_DATA_DIR) + "/test_config/printer.ini";
|
||||
```
|
||||
|
||||
### Available Test Assets
|
||||
|
||||
#### 3D Models
|
||||
- **Basic shapes**: `20mm_cube.obj`, `pyramid.obj`, `sphere.obj`
|
||||
- **Complex geometry**: `extruder_idler.obj`, `ipadstand.obj`, `bridge.obj`
|
||||
- **Edge cases**: `cube_with_hole.obj`, `sloping_hole.obj`, `small_dorito.obj`
|
||||
|
||||
#### File Format Tests
|
||||
- **STL variants**: ASCII/binary, different line endings, Unicode names
|
||||
- **3MF files**: Multi-material, complex assemblies
|
||||
- **Configuration files**: Various printer/material profiles
|
||||
|
||||
#### Test Utilities
|
||||
The `Test` namespace provides helper functions:
|
||||
```cpp
|
||||
using namespace Slic3r::Test;
|
||||
|
||||
// Load standard test meshes
|
||||
TriangleMesh mesh = mesh(TestMesh::cube_20x20x20);
|
||||
|
||||
// Standard test configurations
|
||||
DynamicPrintConfig config = config(TestConfig::PLA_default);
|
||||
```
|
||||
|
||||
## Common Pitfalls and Solutions
|
||||
|
||||
### Floating-Point Comparisons
|
||||
|
||||
> **CRITICAL**: Never use Approx - it's deprecated due to asymmetry and other issues
|
||||
|
||||
❌ **Incorrect**:
|
||||
```cpp
|
||||
REQUIRE(calculated_volume == expected_volume); // Exact equality
|
||||
REQUIRE(calculated_volume == Catch::Approx(expected)); // Deprecated! Asymmetric!
|
||||
```
|
||||
|
||||
✅ **Correct**: Always use floating point matchers
|
||||
```cpp
|
||||
// Absolute tolerance - good when values are near zero
|
||||
REQUIRE_THAT(calculated_volume, WithinAbs(expected_volume, 0.001));
|
||||
|
||||
// Relative tolerance - good for values with different magnitudes
|
||||
REQUIRE_THAT(calculated_volume, WithinRel(expected_volume, 0.01)); // 1% tolerance
|
||||
|
||||
// ULP (Units in Last Place) - most precise, requires IEEE-754
|
||||
REQUIRE_THAT(calculated_volume, WithinULP(expected_volume, 4));
|
||||
|
||||
// Combined approach - relative OR absolute
|
||||
REQUIRE_THAT(calculated_volume,
|
||||
WithinRel(expected_volume, 0.001) || WithinAbs(0.0, 0.000001));
|
||||
|
||||
// Precision control for output
|
||||
Catch::StringMaker<double>::precision = 15; // Show more decimal places
|
||||
```
|
||||
|
||||
### Why Approx is Problematic:
|
||||
- **Asymmetric**: `Approx(10).epsilon(0.1) != 11.1` but `Approx(11.1).epsilon(0.1) == 10`
|
||||
- **Double-only**: All computation done in `double`, causes issues with `float` inputs
|
||||
- **Default behavior**: Only uses relative comparison, so `Approx(0) == X` only works for `X == 0`
|
||||
|
||||
### Path Handling
|
||||
❌ **Incorrect**:
|
||||
```cpp
|
||||
std::string path = TEST_DATA_DIR + "/model.obj"; // May have path separator issues
|
||||
```
|
||||
|
||||
✅ **Correct**:
|
||||
```cpp
|
||||
std::string path = std::string(TEST_DATA_DIR) + "/model.obj";
|
||||
// or use boost::filesystem for complex path operations
|
||||
```
|
||||
|
||||
### Exception Testing
|
||||
❌ **Incorrect**:
|
||||
```cpp
|
||||
bool threw_exception = false;
|
||||
try {
|
||||
risky_function();
|
||||
} catch (...) {
|
||||
threw_exception = true;
|
||||
}
|
||||
REQUIRE(threw_exception);
|
||||
```
|
||||
|
||||
✅ **Correct**:
|
||||
```cpp
|
||||
REQUIRE_THROWS(risky_function());
|
||||
// or for specific exceptions
|
||||
REQUIRE_THROWS_AS(risky_function(), SpecificException);
|
||||
```
|
||||
|
||||
### Thread Safety
|
||||
|
||||
⚠️ **CRITICAL**: Catch2 assertions are **NOT thread-safe** by default!
|
||||
|
||||
> **Note**: Catch2 v3.9.0+ has opt-in thread-safe assertions via `CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS`. OrcaSlicer is on v3.11.0 but does not enable this flag, so assertions remain non-thread-safe by default.
|
||||
|
||||
❌ **Incorrect**: Will cause undefined behavior or crashes
|
||||
```cpp
|
||||
std::thread t([&]() {
|
||||
REQUIRE(threaded_operation() == expected); // NOT THREAD-SAFE!
|
||||
CHECK(other_operation()); // NOT THREAD-SAFE!
|
||||
});
|
||||
```
|
||||
|
||||
✅ **Correct**: Collect results, assert on main thread
|
||||
```cpp
|
||||
std::atomic<bool> success{false};
|
||||
std::atomic<int> error_count{0};
|
||||
|
||||
std::thread t([&]() {
|
||||
// Do work in thread, collect results
|
||||
bool result1 = (threaded_operation() == expected);
|
||||
bool result2 = other_operation();
|
||||
|
||||
if (result1 && result2) {
|
||||
success = true;
|
||||
} else {
|
||||
error_count++;
|
||||
}
|
||||
});
|
||||
|
||||
t.join();
|
||||
|
||||
// Assert results on main thread
|
||||
REQUIRE(success);
|
||||
REQUIRE(error_count == 0);
|
||||
```
|
||||
|
||||
#### Thread Safety Rules:
|
||||
- **REQUIRE family**: Would terminate process in spawned threads (throws exception with no try-catch)
|
||||
- **CHECK family**: Not thread-safe, can corrupt internal state
|
||||
- **SKIP, FAIL, SUCCEED**: Not thread-safe even with v3 thread-safe assertions
|
||||
- **Message macros**: INFO, CAPTURE, WARN - not thread-safe
|
||||
- **STATIC_REQUIRE/CHECK**: Not thread-safe (relies on runtime registration)
|
||||
|
||||
### Memory Management
|
||||
Use RAII and smart pointers in tests:
|
||||
```cpp
|
||||
TEST_CASE("Resource management", "[Memory]") {
|
||||
auto model = std::make_unique<Model>();
|
||||
// Automatic cleanup on test completion/failure
|
||||
|
||||
REQUIRE(model->objects.empty());
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Compilation Optimizations
|
||||
```cpp
|
||||
// In CMakeLists.txt or as preprocessor definition
|
||||
#define CATCH_CONFIG_FAST_COMPILE // 20% faster compilation, disables some features
|
||||
|
||||
// For faster test iteration during development
|
||||
#define CATCH_CONFIG_DISABLE_STRINGIFICATION // Workaround for VS2017 raw string bug
|
||||
```
|
||||
|
||||
### Runtime Performance
|
||||
```cpp
|
||||
TEST_CASE("Performance-sensitive test", "[Performance]") {
|
||||
// Manual timing example (Catch2's built-in BENCHMARK macro is also available)
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
|
||||
auto result = expensive_operation();
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
|
||||
|
||||
REQUIRE(result.is_valid());
|
||||
REQUIRE(duration.count() < 1000); // Should complete in < 1 second
|
||||
|
||||
INFO("Operation took " << duration.count() << "ms");
|
||||
}
|
||||
```
|
||||
|
||||
### Memory Leak Detection
|
||||
```cpp
|
||||
// For Windows builds - detects memory leaks
|
||||
#define CATCH_CONFIG_WINDOWS_CRTDBG // Must be defined for whole build
|
||||
```
|
||||
|
||||
## Integration with CMake
|
||||
|
||||
### Adding New Test Files
|
||||
1. Create test file: `test_new_feature.cpp`
|
||||
2. Add to appropriate `CMakeLists.txt`:
|
||||
```cmake
|
||||
add_executable(${_TEST_NAME}_tests
|
||||
${_TEST_NAME}_tests.cpp
|
||||
test_existing_feature.cpp
|
||||
test_new_feature.cpp # Add here
|
||||
)
|
||||
```
|
||||
|
||||
### Advanced Test Discovery
|
||||
```cmake
|
||||
# Basic test discovery
|
||||
catch_discover_tests(${_TEST_NAME}_tests TEST_PREFIX "${_TEST_NAME}: ")
|
||||
|
||||
# Advanced test discovery with customization
|
||||
catch_discover_tests(${_TEST_NAME}_tests
|
||||
TEST_PREFIX "${_TEST_NAME}: "
|
||||
TEST_SUFFIX " (auto)"
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
EXTRA_ARGS --order rand --warn NoAssertions
|
||||
PROPERTIES
|
||||
TIMEOUT 300
|
||||
LABELS "unit;core"
|
||||
DISCOVERY_MODE PRE_TEST # or POST_BUILD
|
||||
REPORTER junit
|
||||
OUTPUT_DIR ${CMAKE_BINARY_DIR}/test-results
|
||||
OUTPUT_PREFIX "results_"
|
||||
OUTPUT_SUFFIX ".xml"
|
||||
)
|
||||
|
||||
# Test sharding for parallel execution
|
||||
include(CatchShardTests) # If available
|
||||
catch_shard_tests(${_TEST_NAME}_tests
|
||||
SHARD_COUNT 4
|
||||
TEST_PREFIX "${_TEST_NAME}_shard: "
|
||||
)
|
||||
```
|
||||
|
||||
### Conditional Test Compilation
|
||||
```cmake
|
||||
# Feature-dependent tests
|
||||
if (TARGET OpenVDB::openvdb)
|
||||
target_sources(${_TEST_NAME}_tests PRIVATE test_hollowing.cpp)
|
||||
endif()
|
||||
|
||||
# Platform-specific tests
|
||||
if(WIN32)
|
||||
target_sources(${_TEST_NAME}_tests PRIVATE test_windows_specific.cpp)
|
||||
elseif(UNIX)
|
||||
target_sources(${_TEST_NAME}_tests PRIVATE test_unix_specific.cpp)
|
||||
endif()
|
||||
|
||||
# Compiler-specific workarounds
|
||||
if(MSVC)
|
||||
target_compile_definitions(${_TEST_NAME}_tests PRIVATE CATCH_CONFIG_DISABLE_STRINGIFICATION)
|
||||
endif()
|
||||
|
||||
# Fast compile mode for development
|
||||
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
|
||||
target_compile_definitions(${_TEST_NAME}_tests PRIVATE CATCH_CONFIG_FAST_COMPILE)
|
||||
endif()
|
||||
```
|
||||
|
||||
## Known Issues and Workarounds
|
||||
|
||||
### Platform-Specific Issues
|
||||
```cpp
|
||||
// MinGW/CygWin slow linking workaround
|
||||
// Use: -fuse-ld=lld flag to speed up linking significantly
|
||||
|
||||
// Visual Studio 2017 raw string literal bug
|
||||
#define CATCH_CONFIG_DISABLE_STRINGIFICATION
|
||||
// This disables expression stringification but works around the compiler bug
|
||||
|
||||
// Visual Studio 2022 spaceship operator issue
|
||||
// REQUIRE((a <=> b) == 0); // May not compile with MSVC
|
||||
// Workaround: use clang-cl or avoid spaceship in assertions
|
||||
|
||||
// QNX/VxWorks C stdlib issues
|
||||
#include <cfoo> // Use C++ headers
|
||||
std::foo_function(); // Always call qualified
|
||||
// NOT: #include <foo.h> and foo_function();
|
||||
```
|
||||
|
||||
### Catch2 v3 Features Available
|
||||
```cpp
|
||||
// OrcaSlicer is on Catch2 v3.11.0 - all of these ARE available:
|
||||
// SKIP() macro - v3.3.0+
|
||||
// Opt-in thread-safe assertions - v3.9.0+ (NOT enabled here; see Thread Safety)
|
||||
// Built-in BENCHMARK / BENCHMARK_ADVANCED - v3.x
|
||||
// testCasePartial events - v3.0.1+
|
||||
// Multiple reporters simultaneously - v3.0.1+
|
||||
// STATIC_CHECK macro - v3.0.1+
|
||||
// Built-in test sharding (--shard-*) - v3.x
|
||||
|
||||
// v3 notes to remember:
|
||||
// - String matcher is "ContainsSubstring" (v2's "Contains" no longer exists)
|
||||
// - Sections can still be re-run if a later section fails (unchanged from v2)
|
||||
```
|
||||
|
||||
### Test Organization Best Practices
|
||||
|
||||
#### Project Structure Rules
|
||||
1. **1:1 correspondence**: One test binary per library/module
|
||||
2. **Hidden tests**: Use `[.]` or `[!benchmark]` tags for tests that shouldn't run by default
|
||||
3. **Tag hierarchy**: Use consistent tagging scheme across the project
|
||||
4. **File naming**: Follow `test_<feature>.cpp` pattern
|
||||
|
||||
#### CI/CD Integration
|
||||
```bash
|
||||
# Essential CI test command
|
||||
./tests --order rand --warn NoAssertions --reporter junit::out=results.xml
|
||||
|
||||
# For coverage analysis
|
||||
./tests --order rand --warn NoAssertions --reporter console --success
|
||||
|
||||
# For performance tracking
|
||||
./tests --order rand --warn NoAssertions --durations yes
|
||||
```
|
||||
|
||||
This comprehensive guide ensures robust, maintainable, and efficient testing practices for OrcaSlicer development with Claude Code, incorporating all critical knowledge from the official Catch2 documentation.
|
||||
@AGENTS.md
|
||||
|
||||
@@ -13,13 +13,17 @@ endif()
|
||||
set(TEST_DATA_DIR ${CMAKE_CURRENT_SOURCE_DIR}/data)
|
||||
file(TO_NATIVE_PATH "${TEST_DATA_DIR}" TEST_DATA_DIR)
|
||||
|
||||
# Shipped vendor profiles, so tests can exercise the real machine/filament gcode.
|
||||
set(PROFILES_DIR ${CMAKE_SOURCE_DIR}/resources/profiles)
|
||||
file(TO_NATIVE_PATH "${PROFILES_DIR}" PROFILES_DIR)
|
||||
|
||||
include(CTest)
|
||||
include(Catch)
|
||||
|
||||
set(CATCH_EXTRA_ARGS "" CACHE STRING "Extra arguments for catch2 test suites.") # Unknown if this still works and/or should be replaced with something else.
|
||||
|
||||
add_library(test_common INTERFACE)
|
||||
target_compile_definitions(test_common INTERFACE TEST_DATA_DIR=R"\(${TEST_DATA_DIR}\)" CATCH_CONFIG_FAST_COMPILE)
|
||||
target_compile_definitions(test_common INTERFACE TEST_DATA_DIR=R"\(${TEST_DATA_DIR}\)" PROFILES_DIR=R"\(${PROFILES_DIR}\)" CATCH_CONFIG_FAST_COMPILE)
|
||||
target_include_directories(test_common INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
if (APPLE)
|
||||
@@ -57,5 +61,6 @@ add_subdirectory(libslic3r)
|
||||
add_subdirectory(slic3rutils)
|
||||
add_subdirectory(fff_print)
|
||||
add_subdirectory(sla_print)
|
||||
add_subdirectory(filament_group)
|
||||
|
||||
|
||||
|
||||
8
tests/README.md
Normal file
8
tests/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
# OrcaSlicer tests
|
||||
|
||||
Building, running and writing tests is documented on the wiki, under [How to Test](https://www.orcaslicer.com/wiki/developer_reference/how_to_test.html).
|
||||
|
||||
Two files here rather than there, because coding agents only read what is in the repository:
|
||||
|
||||
- [AGENTS.md](AGENTS.md) is the same guidance in short form, and is what an agent working under `tests/` picks up.
|
||||
- [CATCH2.md](CATCH2.md) is the Catch2 reference, including the mistakes that break a test at runtime.
|
||||
88
tests/compare_analyzer/README.md
Normal file
88
tests/compare_analyzer/README.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Compare Analyzer — G-code Slicing Comparison Tools
|
||||
|
||||
Tools for deep comparison and analysis of `.3mf` slicing project files, designed for
|
||||
verifying multi-nozzle (H2C carousel) and multi-extruder slicing correctness.
|
||||
|
||||
## Tools
|
||||
|
||||
### `compare_slices.py` — Slice Comparison Analyzer
|
||||
|
||||
Deep comparison of two `.3mf` files (OrcaSlicer, BambuStudio, or any compatible slicer).
|
||||
Generates a comprehensive Markdown report covering:
|
||||
|
||||
- **Filament usage** — per-filament weight/length with color mapping
|
||||
- **Nozzle/extruder mapping** — Vortek carousel slot assignments
|
||||
- **Tool change sequences** — T-code ordering and count
|
||||
- **Prime tower analysis** — tower entries, G-code line count
|
||||
- **Temperature timeline** — pre-heat lead times, target temperatures per tool change
|
||||
- **Retract parameters** — M620.11 analysis during nozzle switches
|
||||
- **Filament change G-code blocks** — line-by-line diff of change_filament_gcode
|
||||
- **Control command diff** — timeline of M/G-code differences
|
||||
- **Critical discrepancy detection** — automatic flagging of weight/time anomalies
|
||||
|
||||
#### Usage
|
||||
|
||||
```bash
|
||||
# Compare two slice files
|
||||
python3 compare_slices.py file1.3mf file2.3mf
|
||||
|
||||
# With custom labels
|
||||
python3 compare_slices.py file1.3mf file2.3mf --labels "Upstream" "Fixed"
|
||||
```
|
||||
|
||||
#### Output
|
||||
Markdown report saved to `mp_reports/compare_report_YYYYMMDD_HHMMSS.md`
|
||||
|
||||
#### Example: Detecting H2C purge regression
|
||||
```
|
||||
⚠️ CRITICAL DISCREPANCY: Huge difference in part weight:
|
||||
OrcaSlicer 60.90 g vs BambuStudio 17.47 g (difference 43.43 g or 71.3%).
|
||||
The reason is incorrect nozzle mapping, causing huge AMS flushing.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `show_temp_plot.py` — Temperature Timeline Plotter
|
||||
|
||||
Generates interactive HTML temperature plots for analyzing thermal profiles during
|
||||
multi-nozzle prints. Visualizes heater temperature commands (M104/M109) per tool change,
|
||||
showing pre-heat timing and temperature convergence.
|
||||
|
||||
#### Architecture
|
||||
- H2C dual-extruder layout with Vortek carousel nozzles
|
||||
- Physical heaters mapped dynamically:
|
||||
- Heater 0: Extruder 2 (right nozzle slot, T0/T2/T3/T4)
|
||||
- Heater 1: Extruder 1 (left nozzle slot, T1)
|
||||
- Active heater mapping derived from G-code temperature signals
|
||||
|
||||
#### Usage
|
||||
|
||||
```bash
|
||||
# Single file analysis
|
||||
python3 show_temp_plot.py file.3mf
|
||||
|
||||
# Side-by-side comparison of two files
|
||||
python3 show_temp_plot.py file1.3mf file2.3mf
|
||||
```
|
||||
|
||||
#### Output
|
||||
Interactive HTML report saved to Desktop as `temp_plot_v3.html`
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Python 3.8+**
|
||||
- **No external dependencies** — uses only Python standard library
|
||||
(`json`, `zipfile`, `xml.etree.ElementTree`, `difflib`, `webbrowser`)
|
||||
|
||||
## Use Cases
|
||||
|
||||
1. **Regression testing** — compare slices before/after code changes to verify
|
||||
no unintended differences in purge volumes, tool ordering, or temperature timing
|
||||
2. **BBS compatibility verification** — compare OrcaSlicer output against BambuStudio
|
||||
reference slices to ensure behavioral parity
|
||||
3. **H2C carousel validation** — verify per-slot nozzle tracking produces correct
|
||||
purge volumes (not collapsed per-extruder)
|
||||
4. **Temperature protocol analysis** — verify pre-heat lead times and cooling
|
||||
temperatures during nozzle changes match expected profiles
|
||||
1282
tests/compare_analyzer/compare_slices.py
Executable file
1282
tests/compare_analyzer/compare_slices.py
Executable file
File diff suppressed because it is too large
Load Diff
1545
tests/compare_analyzer/show_temp_plot.py
Executable file
1545
tests/compare_analyzer/show_temp_plot.py
Executable file
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_print.cpp
|
||||
test_printobject.cpp
|
||||
test_skirt_brim.cpp
|
||||
test_slicing_pipeline_hook.cpp
|
||||
test_support_material.cpp
|
||||
test_trianglemesh.cpp
|
||||
)
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# fff_print test suite
|
||||
|
||||
Component- and pipeline-level tests for FFF slicing: the path from a `Model` plus config, through `Print` / `PrintObject`, to emitted G-code.
|
||||
|
||||
For Catch2 mechanics (assertions, generators, matchers, random ordering, thread-safety), see [../CLAUDE.md](../CLAUDE.md). This document is the organizing contract for the suite: where a test goes, and how it is named.
|
||||
|
||||
## Organizing principle
|
||||
|
||||
**One file per subsystem. A subsystem is usually a single production class (`Flow`, `PrintObject`), but may be a cohesive feature that spans several (skirt/brim lives in `Brim.cpp`, `Print.cpp`, and `GCode.cpp`). That file owns every test for the subsystem: in-memory-state assertions and emitted-G-code assertions alike.**
|
||||
|
||||
A test's home is decided by *what production code it exercises*, never by *how it observes the result*. A skirt test that inspects `print.skirt()` and one that greps the G-code for `; skirt` live in the same file.
|
||||
|
||||
If you touched code in a subsystem, its test file is where your test goes. If a subsystem has no file yet, add `test_<subsystem>.cpp` and list it in `CMakeLists.txt`.
|
||||
|
||||
## File ownership
|
||||
|
||||
### Building blocks (one class, exercised through its API)
|
||||
|
||||
| File | Source (`src/libslic3r/`) | Covers |
|
||||
|---|---|---|
|
||||
| `test_trianglemesh` | `TriangleMesh.{c,h}pp` | mesh stats, transforms, slicing, split/merge/cut |
|
||||
| `test_flow` | `Flow.{c,h}pp` | extrusion width / area math |
|
||||
| `test_extrusion_entity` | `ExtrusionEntity.{c,h}pp` | extrusion-collection geometry |
|
||||
| `test_gcodewriter` | `GCodeWriter.{c,h}pp`, `GCode.cpp` | low-level G-code emit primitives, origin |
|
||||
| `test_model` | `Model.{c,h}pp` | object / volume / instance construction |
|
||||
|
||||
### Slicing pipeline (build a `Print`, then assert state or G-code)
|
||||
|
||||
| File | Source (`src/libslic3r/`) | Covers |
|
||||
|---|---|---|
|
||||
| `test_printobject` | `PrintObject.cpp` | layer heights, perimeter generation |
|
||||
| `test_fill` | `Fill/` | infill patterns and infill G-code |
|
||||
| `test_skirt_brim` | `Brim.cpp`, `Print.cpp` | skirt/brim loop counts, grouping, brim ears, emission order |
|
||||
| `test_support_material` | `Support/` | support & raft layers, contact distance |
|
||||
| `test_cooling` | `GCode/CoolingBuffer.cpp` | fan control, speed-marker consumption |
|
||||
| `test_multifilament` | `GCode/ToolOrdering.cpp` | per-feature and per-object filament routing |
|
||||
| `test_print` | `Print.{c,h}pp` | `validate()`, solid-shell behavior, sequential printing, custom G-code & config comments, default-slice smoke |
|
||||
|
||||
Paths are under `src/libslic3r/`. A trailing `/` is a directory of related files; otherwise it is a single class. `{c,h}pp` means the `.cpp`/`.hpp` pair.
|
||||
|
||||
## Naming and tags
|
||||
|
||||
- **File:** `test_<subsystem>.cpp`.
|
||||
- **Test name:** a plain behavioral sentence, present tense, stating the contract the test pins down. No `Subsystem:` prefix (the tag carries that).
|
||||
- Good: `TEST_CASE("Skirt is emitted once per layer it spans", "[SkirtBrim]")`
|
||||
- Avoid: `TEST_CASE("Print: Skirt generation", "[Print]")`
|
||||
- **Tags:**
|
||||
- Exactly one **subsystem** tag, PascalCase, matching the file (`[SkirtBrim]`, `[PrintObject]`, `[Fill]`). This is the grouping / filter key.
|
||||
- Optional **cross-cutting** tags for a concern that genuinely spans files (`[validate]`, `[Regression]`).
|
||||
- **Status** tags: `[NotWorking]` marks a test disabled for a known, documented reason; CI excludes it via `~[NotWorking]` (it does not hide itself). Use `[.]` to hide a test from default runs entirely. Either way, say why in a one-line comment.
|
||||
|
||||
## Test style
|
||||
|
||||
Prefer a flat `TEST_CASE` per behavior, with `GENERATE` for parameterized cases and shared setup factored into helpers. The test name carries the behavior, so the BDD scaffolding is usually redundant. Reserve `SCENARIO` / `GIVEN` / `WHEN` / `THEN` for a test with genuine shared setup that branches into a few closely related variations, and never let a `SCENARIO` accumulate unrelated `WHEN`s: that grab-bag is what this contract exists to prevent (and it hides failures behind a single coarse test case).
|
||||
|
||||
## Robust tests
|
||||
|
||||
A test should fail only when the behavior it names breaks, not from unrelated changes (the "change-detector" anti-pattern). Test behavior, not incidentals, and aim for one reason to fail. Concretely:
|
||||
|
||||
- Don't depend on or assert defaults: set the config keys the behavior needs, and derive expected values from those inputs (a 20mm cube at 0.2mm = 100 layers), not from a default that may change.
|
||||
- Assert the defining property, not an incidental value: prefer "skirt present", "at least 2 brim loops", or "ears vs none" over exact coordinates, extrusion amounts, line counts, or byte sizes.
|
||||
- Compare floats with a tolerance (`WithinAbs` / `WithinRel`), never `==`.
|
||||
- Match the meaningful G-code token (`; skirt`), not whole lines, whitespace, or comment wording.
|
||||
- Rely on ordering only when it is the contract (as `role_sequence` does).
|
||||
- Keep tests self-contained: no shared state, green under `--order rand`.
|
||||
|
||||
## Helpers
|
||||
|
||||
Reuse these instead of building a `Print` or parsing G-code by hand.
|
||||
|
||||
- **Global** (`tests/test_utils.hpp`, available to every suite):
|
||||
- `load_model("file.obj")`: load a `TriangleMesh` from `tests/data/`.
|
||||
- `ScopedTemporaryFile`: an RAII temp-file path, removed on scope exit.
|
||||
- **Suite harness** (`fff_print/test_helpers.{hpp,cpp}`):
|
||||
- Build and run: `init_print(...)`, `init_and_process_print(...)`, `slice(...)` (returns the G-code string), and `gcode(print)`.
|
||||
- Two-cube placement: `slice_two_cubes_arranged(...)` (arranger-positioned), and `place_two_cubes_apart(...)` / `slice_two_cubes_apart(...)` (a fixed gap, not arranged).
|
||||
- Meshes: `cube(size)` / `make_cube(...)` for simple shapes; the `TestMesh` enum with `mesh(...)` for named fixtures.
|
||||
- G-code analysis: `layers_with_role(gcode, role)`, `max_z(gcode)`, `role_passes(gcode, role)`, `role_sequence(gcode, roles)`. Subsystem-specific checks stay local (for example `brim_count` in `test_skirt_brim`).
|
||||
|
||||
Promote a helper into the suite harness when it is a general test primitive (not tied to one subsystem's logic), even if only one file uses it today; keep genuinely subsystem-specific helpers local (file-static). Reuse potential, not current usage count, is the test.
|
||||
|
||||
## Adding a test (checklist)
|
||||
|
||||
1. Find the subsystem's file in the tables; create `test_<subsystem>.cpp` if missing.
|
||||
2. Build the print with a harness helper; set only the config keys the behavior needs.
|
||||
3. Assert the behavior, in-memory or via parsed G-code, whichever is clearest.
|
||||
4. Name it as a behavioral sentence and tag it `[Subsystem]`.
|
||||
5. For a bug fix, add the regression test in the owning file. Name it for the behavior it protects; the test must stand on its own without relying on an external issue or PR for meaning.
|
||||
|
||||
## Running
|
||||
|
||||
ctest --test-dir build/tests/fff_print
|
||||
build/tests/fff_print/<config>/fff_print_tests --order rand "~[NotWorking]"
|
||||
@@ -1,12 +1,18 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <map>
|
||||
#include <numeric>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "libslic3r/ClipperUtils.hpp"
|
||||
#include "libslic3r/Fill/Fill.hpp"
|
||||
#include "libslic3r/Flow.hpp"
|
||||
#include "libslic3r/Geometry.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/SVG.hpp"
|
||||
#include "libslic3r/libslic3r.h"
|
||||
@@ -476,3 +482,219 @@ bool test_if_solid_surface_filled(const ExPolygon& expolygon, double flow_spacin
|
||||
|
||||
return uncovered.empty(); // solid surface is fully filled
|
||||
}
|
||||
|
||||
// Length-weighted dominant direction of the layer's role_wanted extrusions, whole degrees
|
||||
// [0, 180), or -1 if it has none. Needs a line pattern such as monotonic or rectilinear.
|
||||
template<typename RolePred> static int dominant_fill_angle(const Layer &layer, RolePred role_wanted)
|
||||
{
|
||||
std::map<int, double> weight_per_degree;
|
||||
|
||||
auto account = [&weight_per_degree, &role_wanted](const ExtrusionPath &path) {
|
||||
if (!role_wanted(path.role()))
|
||||
return;
|
||||
const Points3 &pts = path.polyline.points;
|
||||
for (size_t i = 1; i < pts.size(); ++i) {
|
||||
const double dx = double(pts[i].x() - pts[i - 1].x());
|
||||
const double dy = double(pts[i].y() - pts[i - 1].y());
|
||||
const double len = std::hypot(dx, dy);
|
||||
if (len <= 0.)
|
||||
continue;
|
||||
int deg = int(std::lround(Geometry::rad2deg(std::atan2(dy, dx)))) % 180;
|
||||
if (deg < 0)
|
||||
deg += 180;
|
||||
weight_per_degree[deg] += len;
|
||||
}
|
||||
};
|
||||
|
||||
for (const LayerRegion *region : layer.regions())
|
||||
for (const ExtrusionEntity *entity : region->fills.flatten().entities) {
|
||||
if (auto *path = dynamic_cast<const ExtrusionPath *>(entity))
|
||||
account(*path);
|
||||
else if (auto *multi = dynamic_cast<const ExtrusionMultiPath *>(entity))
|
||||
for (const ExtrusionPath &p : multi->paths)
|
||||
account(p);
|
||||
else if (auto *loop = dynamic_cast<const ExtrusionLoop *>(entity))
|
||||
for (const ExtrusionPath &p : loop->paths)
|
||||
account(p);
|
||||
}
|
||||
|
||||
if (weight_per_degree.empty())
|
||||
return -1;
|
||||
return std::max_element(weight_per_degree.begin(), weight_per_degree.end(),
|
||||
[](const auto &a, const auto &b) { return a.second < b.second; })->first;
|
||||
}
|
||||
|
||||
template<typename RolePred> static std::vector<int> angles_per_layer(const Print &print, RolePred role_wanted)
|
||||
{
|
||||
std::vector<int> angles;
|
||||
for (const Layer *layer : print.objects().front()->layers())
|
||||
angles.push_back(dominant_fill_angle(*layer, role_wanted));
|
||||
return angles;
|
||||
}
|
||||
|
||||
static bool solid_role(ExtrusionRole role) { return is_solid_infill(role) && role != erIroning; }
|
||||
static bool sparse_role(ExtrusionRole role) { return role == erInternalInfill; }
|
||||
static bool ironing_role(ExtrusionRole role) { return role == erIroning; }
|
||||
|
||||
TEST_CASE("Infill rotation template is unaffected by a raft", "[Fill][Regression]")
|
||||
{
|
||||
// More angles than raft layers, so a raft cannot alias back to the same angle.
|
||||
const std::string template_string = GENERATE("+45", "0,25,50,75,100,125,150");
|
||||
const int raft_layers = GENERATE(1, 3);
|
||||
CAPTURE(template_string, raft_layers);
|
||||
|
||||
auto angles_for = [&template_string](int rafts) {
|
||||
Print print;
|
||||
// 100% density makes every layer solid, so the template shows on all 100, not just shells.
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(20)}, print,
|
||||
{{"solid_infill_rotate_template", template_string},
|
||||
{"sparse_infill_density", "100%"},
|
||||
{"internal_solid_infill_pattern", "monotonic"},
|
||||
{"layer_height", 0.2},
|
||||
{"raft_layers", rafts}});
|
||||
return angles_per_layer(print, solid_role);
|
||||
};
|
||||
|
||||
const std::vector<int> without_raft = angles_for(0);
|
||||
const std::vector<int> with_raft = angles_for(raft_layers);
|
||||
|
||||
REQUIRE(without_raft.size() == 100);
|
||||
REQUIRE(with_raft.size() == without_raft.size());
|
||||
REQUIRE(std::count(without_raft.begin(), without_raft.end(), -1) == 0);
|
||||
CHECK(with_raft == without_raft);
|
||||
}
|
||||
|
||||
TEST_CASE("Sparse infill rotation template turns the infill layer by layer", "[Fill]")
|
||||
{
|
||||
const std::vector<int> expected_cycle = {0, 25, 50, 75, 100, 125, 150};
|
||||
|
||||
Print print;
|
||||
// No shells, so every layer is sparse infill rather than solid.
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(10)}, print,
|
||||
{{"sparse_infill_rotate_template", "0,25,50,75,100,125,150"},
|
||||
{"sparse_infill_density", "40%"},
|
||||
{"sparse_infill_pattern", "rectilinear"},
|
||||
{"top_shell_layers", 0},
|
||||
{"bottom_shell_layers", 0},
|
||||
{"layer_height", 0.2}});
|
||||
|
||||
const std::vector<int> angles = angles_per_layer(print, sparse_role);
|
||||
REQUIRE(angles.size() == 50);
|
||||
REQUIRE(std::count(angles.begin(), angles.end(), -1) == 0);
|
||||
|
||||
std::vector<int> expected;
|
||||
for (size_t i = 0; i < angles.size(); ++i)
|
||||
expected.push_back(expected_cycle[i % expected_cycle.size()]);
|
||||
CHECK(angles == expected);
|
||||
}
|
||||
|
||||
TEST_CASE("Infill rotation template layer count modifier holds each angle for N layers", "[Fill]")
|
||||
{
|
||||
Print print;
|
||||
// "+45#2" turns 45 degrees every 2 layers, so equal angles come in pairs.
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(10)}, print,
|
||||
{{"solid_infill_rotate_template", "+45#2"},
|
||||
{"sparse_infill_density", "100%"},
|
||||
{"internal_solid_infill_pattern", "monotonic"},
|
||||
{"layer_height", 0.2}});
|
||||
|
||||
const std::vector<int> angles = angles_per_layer(print, solid_role);
|
||||
REQUIRE(angles.size() == 50);
|
||||
REQUIRE(std::count(angles.begin(), angles.end(), -1) == 0);
|
||||
|
||||
std::vector<int> run_lengths;
|
||||
for (size_t i = 0; i < angles.size();) {
|
||||
size_t j = i;
|
||||
while (j < angles.size() && angles[j] == angles[i])
|
||||
++j;
|
||||
run_lengths.push_back(int(j - i));
|
||||
i = j;
|
||||
}
|
||||
// The first and last runs can be clipped by the start and end of the object.
|
||||
REQUIRE(run_lengths.size() > 3);
|
||||
const std::vector<int> interior(run_lengths.begin() + 1, run_lengths.end() - 1);
|
||||
CHECK(std::count(interior.begin(), interior.end(), 2) == int(interior.size()));
|
||||
}
|
||||
|
||||
TEST_CASE("Z anti-aliasing keeps the infill rotation template's step", "[Fill]")
|
||||
{
|
||||
Print print;
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(10)}, print,
|
||||
{{"solid_infill_rotate_template", "+45"},
|
||||
{"sparse_infill_density", "100%"},
|
||||
{"internal_solid_infill_pattern", "monotonic"},
|
||||
{"zaa_enabled", 1},
|
||||
{"zaa_min_z", 0.05},
|
||||
{"layer_height", 0.2}});
|
||||
|
||||
// Z contouring varies the layer heights, so the layer count is not 10mm / 0.2mm here.
|
||||
const std::vector<int> angles = angles_per_layer(print, solid_role);
|
||||
REQUIRE(angles.size() > 10);
|
||||
REQUIRE(std::count(angles.begin(), angles.end(), -1) == 0);
|
||||
|
||||
// Z contouring may change when the template advances, but each step must still be 45 degrees.
|
||||
int steps = 0;
|
||||
for (size_t i = 1; i < angles.size(); ++i) {
|
||||
const int delta = ((angles[i] - angles[i - 1]) % 180 + 180) % 180;
|
||||
CAPTURE(i, angles[i - 1], angles[i]);
|
||||
// Split rather than "delta == 0 || delta == 45" so Catch2 can show the operands.
|
||||
REQUIRE(delta % 45 == 0);
|
||||
REQUIRE(delta <= 45);
|
||||
steps += delta == 45;
|
||||
}
|
||||
CHECK(steps > 0);
|
||||
}
|
||||
|
||||
TEST_CASE("Ironing follows the solid infill rotation template", "[Fill]")
|
||||
{
|
||||
Print print;
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(10)}, print,
|
||||
{{"solid_infill_rotate_template", "+45"},
|
||||
{"internal_solid_infill_pattern", "monotonic"},
|
||||
{"top_surface_pattern", "monotonic"},
|
||||
// Every solid surface, so the comparison covers every layer.
|
||||
{"ironing_type", "solid"},
|
||||
{"sparse_infill_density", "100%"},
|
||||
{"ironing_angle", 0},
|
||||
{"ironing_angle_fixed", 0},
|
||||
{"layer_height", 0.2}});
|
||||
|
||||
const std::vector<int> ironing = angles_per_layer(print, ironing_role);
|
||||
const std::vector<int> solid = angles_per_layer(print, solid_role);
|
||||
REQUIRE(ironing.size() == solid.size());
|
||||
|
||||
// With no fixed angle and no offset, ironing runs along the template's angle for that layer.
|
||||
int compared = 0;
|
||||
for (size_t i = 0; i < ironing.size(); ++i)
|
||||
if (ironing[i] != -1 && solid[i] != -1) {
|
||||
CAPTURE(i, ironing[i], solid[i]);
|
||||
CHECK(ironing[i] == solid[i]);
|
||||
++compared;
|
||||
}
|
||||
// Most of the object, not one lucky layer.
|
||||
REQUIRE(compared > int(ironing.size()) / 2);
|
||||
}
|
||||
|
||||
TEST_CASE("Solid infill direction offsets every layer when no template is set", "[Fill]")
|
||||
{
|
||||
auto angles_for = [](int direction) {
|
||||
Print print;
|
||||
Slic3r::Test::init_and_process_print({Slic3r::Test::cube(10)}, print,
|
||||
{{"solid_infill_direction", direction},
|
||||
{"sparse_infill_density", "100%"},
|
||||
{"internal_solid_infill_pattern", "monotonic"},
|
||||
{"layer_height", 0.2}});
|
||||
return angles_per_layer(print, solid_role);
|
||||
};
|
||||
|
||||
const std::vector<int> at_0 = angles_for(0);
|
||||
const std::vector<int> at_30 = angles_for(30);
|
||||
REQUIRE(at_0.size() == at_30.size());
|
||||
REQUIRE(std::count(at_0.begin(), at_0.end(), -1) == 0);
|
||||
|
||||
for (size_t i = 0; i < at_0.size(); ++i) {
|
||||
const int delta = ((at_30[i] - at_0[i]) % 180 + 180) % 180;
|
||||
CAPTURE(i, at_0[i], at_30[i]);
|
||||
CHECK(delta == 30);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
#include "libslic3r/libslic3r.h"
|
||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||
#include "libslic3r/MultiNozzleUtils.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
#include "test_utils.hpp"
|
||||
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
|
||||
using namespace Slic3r;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
@@ -323,3 +325,96 @@ TEST_CASE("Carried-forward tool-change delay reaches the total without polluting
|
||||
REQUIRE_THAT(rd.at(role), WithinAbs(zero_time, 1e-2));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Per-slot machine limits follow the active nozzle", "[GCodeTiming][MultiNozzle]")
|
||||
{
|
||||
// Single physical extruder carrying two nozzle variants: machine slot 0 (Standard) caps X/Y
|
||||
// speed at 200 mm/s, slot 1 (High Flow) at 50 mm/s. The estimator must clamp each move by the
|
||||
// slot of the nozzle the active filament occupies -- resolved from the grouping context handed
|
||||
// over before the replay plus the occupancy recorder, i.e. the exact in-slicer streaming path.
|
||||
FullPrintConfig config = make_config(0.0, 0.0, 0.0);
|
||||
config.extruder_type.values = {static_cast<int>(etDirectDrive)};
|
||||
config.printer_extruder_id.values = {1, 1};
|
||||
config.printer_extruder_variant.values = {"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
// Slot-major layout: [slot0-Normal, slot0-Stealth, slot1-Normal, slot1-Stealth].
|
||||
config.machine_max_speed_x.values = {200., 200., 50., 50.};
|
||||
config.machine_max_speed_y.values = {200., 200., 50., 50.};
|
||||
config.machine_max_speed_z.values = {200., 200., 50., 50.};
|
||||
config.machine_max_speed_e.values = {200., 200., 50., 50.};
|
||||
// Keep acceleration and jerk far from limiting so move times are speed-dominated.
|
||||
for (auto *accel : {&config.machine_max_acceleration_x, &config.machine_max_acceleration_y,
|
||||
&config.machine_max_acceleration_z, &config.machine_max_acceleration_e})
|
||||
accel->values = {100000., 100000., 100000., 100000.};
|
||||
config.machine_max_acceleration_travel.values = {100000., 100000.};
|
||||
config.machine_max_acceleration_extruding.values = {100000., 100000.};
|
||||
config.machine_max_jerk_x.values = {10000., 10000.};
|
||||
config.machine_max_jerk_y.values = {10000., 10000.};
|
||||
config.machine_max_jerk_z.values = {10000., 10000.};
|
||||
config.machine_max_jerk_e.values = {10000., 10000.};
|
||||
|
||||
// Grouping stub: filament 0 lives on the Standard nozzle (slot 0), filament 1 on the
|
||||
// High Flow nozzle (slot 1), both mounted on extruder 0.
|
||||
std::vector<MultiNozzleUtils::NozzleInfo> nozzles;
|
||||
{
|
||||
MultiNozzleUtils::NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard; n.extruder_id = 0; n.group_id = 0; nozzles.push_back(n);
|
||||
n.volume_type = nvtHighFlow; n.extruder_id = 0; n.group_id = 1; nozzles.push_back(n);
|
||||
}
|
||||
std::vector<int> filament_nozzle_map = {0, 1};
|
||||
std::vector<unsigned int> used_filaments = {0, 1};
|
||||
auto group = MultiNozzleUtils::LayeredNozzleGroupResult::create(filament_nozzle_map, nozzles, used_filaments);
|
||||
REQUIRE(group.has_value());
|
||||
auto context = std::make_shared<MultiNozzleUtils::LayeredNozzleGroupResult>(*group);
|
||||
|
||||
// Two identical 100 mm X travels, one per filament; T..H.. carries the target nozzle id.
|
||||
// The trailing 1 mm move keeps two blocks queued at finalize, so the measured move's time is
|
||||
// flushed (a lone final block is never attributed); it adds 1 mm to the second bucket.
|
||||
const char* gcode =
|
||||
"M83\n"
|
||||
"T0 H0\n"
|
||||
"G1 X100 F30000\n"
|
||||
"T1 H1\n"
|
||||
"G1 X0 F30000\n"
|
||||
"G1 X1 F30000\n";
|
||||
|
||||
// Travel time accumulated after each tool-change move (bucket 0 = before any T).
|
||||
auto travel_times_by_tool = [](const GCodeProcessorResult& r) {
|
||||
std::vector<double> out(1, 0.0);
|
||||
for (const auto& mv : r.moves) {
|
||||
if (mv.type == EMoveType::Tool_change)
|
||||
out.push_back(0.0);
|
||||
else if (mv.type == EMoveType::Travel)
|
||||
out.back() += mv.time[NORMAL];
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
SECTION("the move on the High Flow nozzle is clamped by its own slot") {
|
||||
GCodeProcessor proc;
|
||||
proc.initialize_from_context(context);
|
||||
run_processor(proc, config, gcode);
|
||||
auto times = travel_times_by_tool(proc.get_result());
|
||||
REQUIRE(times.size() == 3);
|
||||
REQUIRE_THAT(times[1], Catch::Matchers::WithinRel(100.0 / 200.0, 0.10));
|
||||
REQUIRE_THAT(times[2], Catch::Matchers::WithinRel(101.0 / 50.0, 0.10));
|
||||
}
|
||||
SECTION("an emitted envelope line reaches every slot") {
|
||||
const std::string enveloped = std::string("M201 X20000\nM203 X80\n") + gcode;
|
||||
GCodeProcessor proc;
|
||||
proc.initialize_from_context(context);
|
||||
run_processor(proc, config, enveloped.c_str());
|
||||
auto times = travel_times_by_tool(proc.get_result());
|
||||
REQUIRE(times.size() == 3);
|
||||
REQUIRE_THAT(times[1], Catch::Matchers::WithinRel(100.0 / 80.0, 0.10));
|
||||
REQUIRE_THAT(times[2], Catch::Matchers::WithinRel(101.0 / 80.0, 0.10));
|
||||
}
|
||||
SECTION("no grouping context degrades to slot 0") {
|
||||
GCodeProcessor proc;
|
||||
run_processor(proc, config, gcode);
|
||||
auto times = travel_times_by_tool(proc.get_result());
|
||||
REQUIRE(times.size() == 3);
|
||||
REQUIRE_THAT(times[1], Catch::Matchers::WithinRel(100.0 / 200.0, 0.10));
|
||||
REQUIRE_THAT(times[2], Catch::Matchers::WithinRel(101.0 / 200.0, 0.10));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "libslic3r/GCodeWriter.hpp"
|
||||
#include "libslic3r/GCode.hpp"
|
||||
@@ -8,11 +12,23 @@
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/ModelArrange.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include "test_helpers.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
|
||||
// Arrange on a finite bed, not an unbounded InfiniteBed: the latter places items
|
||||
// near INT64_MIN/4 (~2.3e18), which reaches ClipperLib's coordinate limit and throws
|
||||
// "Coordinate outside allowed range" on Windows/arm64. A 500x500 bed keeps coordinates
|
||||
// small while still covering large printers.
|
||||
static void arrange_objects_on_test_bed(Model &model, const DynamicPrintConfig &config)
|
||||
{
|
||||
const BoundingBox bed{Point::new_scale(0., 0.), Point::new_scale(500., 500.)};
|
||||
arrange_objects(model, bed, ArrangeParams{scaled(min_object_distance(config))});
|
||||
}
|
||||
|
||||
SCENARIO("set_speed emits values with fixed-point output.", "[GCodeWriter]") {
|
||||
|
||||
GIVEN("GCodeWriter instance") {
|
||||
@@ -241,8 +257,7 @@ TEST_CASE("Machine envelope emits max limit among used extruders", "[GCodeWriter
|
||||
obj2->config.set_key_value("extruder", new ConfigOptionInt(2)); // 0-based index 1
|
||||
|
||||
Print print;
|
||||
arrange_objects(model, InfiniteBed{},
|
||||
ArrangeParams{scaled(min_object_distance(config))});
|
||||
arrange_objects_on_test_bed(model, config);
|
||||
for (auto* mo : model.objects) {
|
||||
mo->ensure_on_bed();
|
||||
print.auto_assign_extruders(mo);
|
||||
@@ -354,7 +369,7 @@ TEST_CASE("EXTRUDER_LIMIT per-extruder clamping and max fallback", "[GCodeWriter
|
||||
obj2->config.set_key_value("extruder", new ConfigOptionInt(2)); // 0-based index 1
|
||||
|
||||
Print print;
|
||||
arrange_objects(model, InfiniteBed{}, ArrangeParams{scaled(min_object_distance(config))});
|
||||
arrange_objects_on_test_bed(model, config);
|
||||
for (auto* mo : model.objects) {
|
||||
mo->ensure_on_bed();
|
||||
print.auto_assign_extruders(mo);
|
||||
@@ -404,3 +419,431 @@ TEST_CASE("EXTRUDER_LIMIT per-extruder clamping and max fallback", "[GCodeWriter
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Extruder reads the injected config column", "[GCodeWriter][H2C]") {
|
||||
GIVEN("A writer whose per-variant arrays hold three columns for two filaments") {
|
||||
GCodeWriter writer;
|
||||
// Column layout after a migrating regroup: filament 0 -> column 0, filament 1 ->
|
||||
// columns 1 (its first variant) and 2 (its second variant).
|
||||
writer.config.retraction_length.values = {0.8, 0.5, 1.2};
|
||||
writer.config.z_hop.values = {0.4, 0.6, 0.9};
|
||||
writer.config.retraction_speed.values = {30., 40., 50.};
|
||||
writer.config.filament_flow_ratio.values = {0.98, 1.0, 1.02};
|
||||
// Filament-indexed arrays keep one entry per filament.
|
||||
writer.config.filament_diameter.values = {1.75, 1.75};
|
||||
writer.set_extruders({0, 1});
|
||||
writer.toolchange(1, 1);
|
||||
Extruder *fil = writer.filament();
|
||||
REQUIRE(fil != nullptr);
|
||||
REQUIRE(fil->id() == 1);
|
||||
const double crossection = 1.75 * 1.75 * 0.25 * PI;
|
||||
|
||||
WHEN("no column has been injected") {
|
||||
THEN("the getters read the filament id's column") {
|
||||
REQUIRE(fil->config_index() == 1);
|
||||
REQUIRE_THAT(fil->retraction_length(), Catch::Matchers::WithinAbs(0.5, 1e-9));
|
||||
REQUIRE_THAT(fil->retract_lift(), Catch::Matchers::WithinAbs(0.6, 1e-9));
|
||||
REQUIRE(fil->retract_speed() == 40);
|
||||
REQUIRE_THAT(fil->e_per_mm3(), Catch::Matchers::WithinRel(1.0 / crossection, 1e-9));
|
||||
}
|
||||
}
|
||||
WHEN("the second variant column is injected") {
|
||||
fil->set_config_index(2);
|
||||
THEN("the getters follow the column and the flow cache is rescaled") {
|
||||
REQUIRE(fil->config_index() == 2);
|
||||
REQUIRE_THAT(fil->retraction_length(), Catch::Matchers::WithinAbs(1.2, 1e-9));
|
||||
REQUIRE_THAT(fil->retract_lift(), Catch::Matchers::WithinAbs(0.9, 1e-9));
|
||||
REQUIRE(fil->retract_speed() == 50);
|
||||
REQUIRE_THAT(fil->e_per_mm3(), Catch::Matchers::WithinRel(1.02 / crossection, 1e-9));
|
||||
}
|
||||
THEN("filament-indexed reads keep using the filament id") {
|
||||
REQUIRE_THAT(fil->filament_diameter(), Catch::Matchers::WithinAbs(1.75, 1e-9));
|
||||
}
|
||||
}
|
||||
WHEN("a negative index is injected") {
|
||||
fil->set_config_index(2);
|
||||
fil->set_config_index(-1);
|
||||
THEN("resolution resets to the filament id") {
|
||||
REQUIRE(fil->config_index() == 1);
|
||||
REQUIRE_THAT(fil->retraction_length(), Catch::Matchers::WithinAbs(0.5, 1e-9));
|
||||
REQUIRE_THAT(fil->e_per_mm3(), Catch::Matchers::WithinRel(1.0 / crossection, 1e-9));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Numeric argument of every line starting with `prefix`, in file order.
|
||||
static std::vector<int> collect_line_args(const std::string &gcode, const std::string &prefix)
|
||||
{
|
||||
std::vector<int> values;
|
||||
std::istringstream stream(gcode);
|
||||
std::string line;
|
||||
while (std::getline(stream, line))
|
||||
if (line.compare(0, prefix.size(), prefix) == 0)
|
||||
values.push_back(std::atoi(line.c_str() + int(prefix.size())));
|
||||
return values;
|
||||
}
|
||||
|
||||
static int count_lines_with_prefix(const std::string &gcode, const std::string &prefix)
|
||||
{
|
||||
return (int) collect_line_args(gcode, prefix).size();
|
||||
}
|
||||
|
||||
// A toolchange ordinal sequence is healthy when it advances by exactly one per
|
||||
// change block; a change-less prime-tower visit must not consume an ordinal.
|
||||
static bool ordinals_consecutive(const std::vector<int> &values)
|
||||
{
|
||||
for (size_t i = 1; i < values.size(); ++i)
|
||||
if (values[i] != values[i - 1] + 1)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
SCENARIO("Toolchange emission and prefix per printer kind", "[GCodeWriter][H2C]") {
|
||||
GIVEN("A dual-extruder writer with two filaments") {
|
||||
GCodeWriter writer;
|
||||
writer.config.filament_diameter.values = {1.75, 1.75};
|
||||
writer.set_extruders({0, 1});
|
||||
|
||||
WHEN("the printer is a BBL machine") {
|
||||
writer.set_is_bbl_machine(true);
|
||||
THEN("the toolchange prefix is the plain T command") {
|
||||
REQUIRE_THAT(writer.toolchange_prefix(), Catch::Matchers::Equals("T"));
|
||||
}
|
||||
THEN("toolchange emits a single M1020 with the nozzle id") {
|
||||
const std::string gcode = writer.toolchange(1, 0);
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring("M1020 S1 H0"));
|
||||
REQUIRE_THAT(gcode, !Catch::Matchers::StartsWith("T1"));
|
||||
}
|
||||
THEN("the other filament and nozzle emit their own ids") {
|
||||
REQUIRE_THAT(writer.toolchange(0, 1), Catch::Matchers::ContainsSubstring("M1020 S0 H1"));
|
||||
}
|
||||
THEN("an unresolved nozzle keeps the literal -1 convention") {
|
||||
REQUIRE_THAT(writer.toolchange(1, -1), Catch::Matchers::ContainsSubstring("M1020 S1 H-1"));
|
||||
}
|
||||
}
|
||||
WHEN("the printer is a BBL machine with manual filament change") {
|
||||
writer.set_is_bbl_machine(true);
|
||||
writer.config.manual_filament_change.value = true;
|
||||
THEN("the manual tag wins over the M1020 form") {
|
||||
REQUIRE_THAT(writer.toolchange_prefix(), Catch::Matchers::StartsWith(";"));
|
||||
const std::string gcode = writer.toolchange(1, 0);
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring(writer.toolchange_prefix() + "1"));
|
||||
REQUIRE_THAT(gcode, !Catch::Matchers::ContainsSubstring("M1020"));
|
||||
}
|
||||
}
|
||||
WHEN("the printer is not a BBL machine") {
|
||||
THEN("toolchange keeps the plain T command") {
|
||||
REQUIRE_THAT(writer.toolchange_prefix(), Catch::Matchers::Equals("T"));
|
||||
const std::string gcode = writer.toolchange(1, 0);
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::StartsWith("T1"));
|
||||
REQUIRE_THAT(gcode, !Catch::Matchers::ContainsSubstring("M1020"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Shared dual-extruder printer config for the toolchange-count scenarios below.
|
||||
static DynamicPrintConfig dual_extruder_toolchange_config()
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("gcode_flavor", new ConfigOptionEnum<GCodeFlavor>(gcfMarlinFirmware));
|
||||
config.set_key_value("emit_machine_limits_to_gcode", new ConfigOptionBool(false));
|
||||
config.set_key_value("machine_start_gcode", new ConfigOptionString(""));
|
||||
config.set_key_value("layer_height", new ConfigOptionFloat(0.2));
|
||||
config.set_key_value("initial_layer_print_height", new ConfigOptionFloat(0.2));
|
||||
config.set_key_value("initial_layer_line_width", new ConfigOptionFloatOrPercent(0, false));
|
||||
config.set_key_value("z_hop", new ConfigOptionFloats({0., 0.}));
|
||||
// The change block carries both a real toolchange command and the ordinal
|
||||
// placeholder the stock profiles feed to the firmware.
|
||||
config.set_key_value("change_filament_gcode",
|
||||
new ConfigOptionString("T[next_filament_id]\nM620 O{toolchange_count + 1}\n"));
|
||||
|
||||
// 2 extruders, one filament each (manual map so nothing regroups them).
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({0.4, 0.4}));
|
||||
config.set_key_value("printer_extruder_id", new ConfigOptionInts({1, 2}));
|
||||
config.set_key_value("printer_extruder_variant", new ConfigOptionStrings({"Direct Drive Standard", "Direct Drive Standard"}));
|
||||
config.set_key_value("filament_diameter", new ConfigOptionFloats({1.75, 1.75}));
|
||||
config.set_key_value("filament_colour", new ConfigOptionStrings({"#FF0000", "#00FF00"}));
|
||||
config.set_key_value("default_filament_colour", new ConfigOptionStrings({"#FF0000", "#00FF00"}));
|
||||
config.set_key_value("filament_type", new ConfigOptionStrings({"PLA", "PLA"}));
|
||||
config.option<ConfigOptionEnum<FilamentMapMode>>("filament_map_mode", true)->value = fmmManual;
|
||||
config.set_key_value("filament_map", new ConfigOptionInts({1, 2}));
|
||||
config.set_key_value("nozzle_temperature", new ConfigOptionInts({210, 210}));
|
||||
config.set_key_value("nozzle_temperature_range_low", new ConfigOptionInts({190, 190}));
|
||||
config.set_key_value("nozzle_temperature_range_high", new ConfigOptionInts({240, 240}));
|
||||
config.set_key_value("flush_multiplier", new ConfigOptionFloats({1}));
|
||||
config.set_key_value("flush_volumes_matrix", new ConfigOptionFloats({0, 140, 140, 0}));
|
||||
return config;
|
||||
}
|
||||
|
||||
SCENARIO("Change blocks carry consecutive toolchange ordinals without a duplicate command", "[GCodeWriter][H2C]") {
|
||||
GIVEN("Two sequentially printed objects on different extruders of a BBL machine") {
|
||||
DynamicPrintConfig config = dual_extruder_toolchange_config();
|
||||
config.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
|
||||
|
||||
Model model;
|
||||
auto *obj1 = model.add_object();
|
||||
obj1->add_volume(cube(20));
|
||||
obj1->add_instance();
|
||||
auto *obj2 = model.add_object();
|
||||
obj2->add_volume(cube(20));
|
||||
obj2->add_instance();
|
||||
obj2->config.set_key_value("extruder", new ConfigOptionInt(2));
|
||||
|
||||
auto slice_to_gcode = [&]() {
|
||||
Print print;
|
||||
print.is_BBL_printer() = true;
|
||||
arrange_objects_on_test_bed(model, config);
|
||||
for (auto *mo : model.objects) {
|
||||
mo->ensure_on_bed();
|
||||
print.auto_assign_extruders(mo);
|
||||
}
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
print.process();
|
||||
return Slic3r::Test::gcode(print);
|
||||
};
|
||||
|
||||
WHEN("the change block already changes the tool") {
|
||||
const std::string gcode = slice_to_gcode();
|
||||
const std::vector<int> ordinals = collect_line_args(gcode, "M620 O");
|
||||
THEN("each change block advances the ordinal by exactly one, without inflation") {
|
||||
REQUIRE(!ordinals.empty());
|
||||
REQUIRE(ordinals_consecutive(ordinals));
|
||||
REQUIRE(ordinals.front() <= 3);
|
||||
}
|
||||
THEN("the writer's own command is suppressed as a duplicate") {
|
||||
REQUIRE(count_lines_with_prefix(gcode, "M1020") == 0);
|
||||
REQUIRE(count_lines_with_prefix(gcode, "T1") >= 1);
|
||||
}
|
||||
}
|
||||
WHEN("the change block does not change the tool itself") {
|
||||
config.set_key_value("change_filament_gcode",
|
||||
new ConfigOptionString("M620 O{toolchange_count + 1}\n"));
|
||||
const std::string gcode = slice_to_gcode();
|
||||
const std::vector<int> ordinals = collect_line_args(gcode, "M620 O");
|
||||
THEN("the writer's toolchange survives and carries a nozzle id") {
|
||||
REQUIRE(count_lines_with_prefix(gcode, "M1020 S1 H") >= 1);
|
||||
}
|
||||
THEN("the ordinal sequence stays consecutive") {
|
||||
REQUIRE(!ordinals.empty());
|
||||
REQUIRE(ordinals_consecutive(ordinals));
|
||||
REQUIRE(ordinals.front() <= 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Prime-tower visits without a filament change do not advance the toolchange ordinal", "[GCodeWriter][H2C]") {
|
||||
GIVEN("A print whose only filament change happens far above the bed") {
|
||||
DynamicPrintConfig config = dual_extruder_toolchange_config();
|
||||
config.set_key_value("enable_prime_tower", new ConfigOptionBool(true));
|
||||
|
||||
// Filament 2 is used only above z=6, so every tower layer below it is a
|
||||
// change-less visit — the exact geometry that used to inflate the ordinal.
|
||||
Model model;
|
||||
auto *obj = model.add_object();
|
||||
obj->add_volume(cube(10));
|
||||
obj->add_instance();
|
||||
DynamicPrintConfig range_config;
|
||||
range_config.set_key_value("extruder", new ConfigOptionInt(2));
|
||||
// Every layer range must carry a layer_height (see layer_height_profile_from_ranges).
|
||||
range_config.set_key_value("layer_height", new ConfigOptionFloat(0.2));
|
||||
obj->layer_config_ranges[{6.0, 10.0}].assign_config(std::move(range_config));
|
||||
|
||||
Print print;
|
||||
print.is_BBL_printer() = true;
|
||||
arrange_objects_on_test_bed(model, config);
|
||||
for (auto *mo : model.objects) {
|
||||
mo->ensure_on_bed();
|
||||
print.auto_assign_extruders(mo);
|
||||
}
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
print.process();
|
||||
const std::string gcode = Slic3r::Test::gcode(print);
|
||||
|
||||
WHEN("the print is exported") {
|
||||
const std::vector<int> ordinals = collect_line_args(gcode, "M620 O");
|
||||
THEN("the prime-tower toolchange path was exercised") {
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring("CP TOOLCHANGE START"));
|
||||
}
|
||||
THEN("dozens of change-less tower layers consume no ordinal") {
|
||||
REQUIRE(!ordinals.empty());
|
||||
REQUIRE(ordinals_consecutive(ordinals));
|
||||
REQUIRE(ordinals.front() <= 3);
|
||||
}
|
||||
THEN("no duplicate toolchange command follows the change block") {
|
||||
REQUIRE(count_lines_with_prefix(gcode, "M1020") == 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Real-profile toolchange coverage, targeted. The all-vendors sweep in test_profile_slicing.cpp now
|
||||
// slices a two-colour cube per printer, so it already expands every shipped change_filament_gcode with
|
||||
// each printer's DEFAULT extruder variants (both the single-nozzle append_tcr and dual-nozzle set_extruder
|
||||
// paths). What that sweep can't reach is a variant-conditional branch the defaults never select — H2D's
|
||||
// change gcode has an `== "Direct Drive TPU High Flow"` block. This scenario forces that branch by handing
|
||||
// the extruders distinct kits, so an unregistered placeholder inside it still throws "Variable does not
|
||||
// exist" here instead of only in the field.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Two 20mm cubes on separate extruders of a BBL machine, printed by object so exactly
|
||||
// one real toolchange fires and drives the change_filament_gcode. Returns the g-code.
|
||||
static std::string slice_two_object_bbl(DynamicPrintConfig &config)
|
||||
{
|
||||
config.set_key_value("print_sequence", new ConfigOptionEnum<PrintSequence>(PrintSequence::ByObject));
|
||||
|
||||
Model model;
|
||||
auto *obj1 = model.add_object();
|
||||
obj1->add_volume(cube(20));
|
||||
obj1->add_instance();
|
||||
auto *obj2 = model.add_object();
|
||||
obj2->add_volume(cube(20));
|
||||
obj2->add_instance();
|
||||
obj2->config.set_key_value("extruder", new ConfigOptionInt(2));
|
||||
|
||||
Print print;
|
||||
print.is_BBL_printer() = true;
|
||||
arrange_objects_on_test_bed(model, config);
|
||||
for (auto *mo : model.objects) {
|
||||
mo->ensure_on_bed();
|
||||
print.auto_assign_extruders(mo);
|
||||
}
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
print.process();
|
||||
return Slic3r::Test::gcode(print);
|
||||
}
|
||||
|
||||
// The real change_filament_gcode of a shipped "<printer> 0.4 nozzle" machine profile.
|
||||
static std::string shipped_change_filament_gcode(const std::string &printer)
|
||||
{
|
||||
const std::string path = std::string(PROFILES_DIR) + "/BBL/machine/Bambu Lab " + printer + " 0.4 nozzle.json";
|
||||
// PROFILES_DIR is an absolute path baked in at build time; a sparse test checkout
|
||||
// without resources/ leaves it missing. Skip rather than dereference a config that
|
||||
// never loaded - this is the only fff_print test that reads a shipped profile.
|
||||
if (!boost::filesystem::exists(path))
|
||||
SKIP("shipped profile not present in this checkout: " << path);
|
||||
DynamicPrintConfig config;
|
||||
std::map<std::string, std::string> key_values;
|
||||
std::string reason;
|
||||
config.load_from_json(path, ForwardCompatibilitySubstitutionRule::Enable, key_values, reason);
|
||||
// Fail loudly on a malformed/renamed profile instead of null-dereferencing in opt_string.
|
||||
INFO("profile: " << path << (reason.empty() ? "" : (" load reason: " + reason)));
|
||||
REQUIRE(config.has("change_filament_gcode"));
|
||||
return config.opt_string("change_filament_gcode");
|
||||
}
|
||||
|
||||
SCENARIO("Toolchange gcode resolves old/new_extruder_variant from printer_extruder_variant", "[GCodeWriter][H2C]")
|
||||
{
|
||||
GIVEN("a BBL dual-extruder print whose change gcode reads the extruder-variant placeholders") {
|
||||
DynamicPrintConfig config = dual_extruder_toolchange_config();
|
||||
// A distinctive variant that can only reach the g-code through printer_extruder_variant.
|
||||
// Both entries carry it so the assertion is independent of which physical extruder the
|
||||
// emitted change routes through.
|
||||
config.set_key_value("printer_extruder_variant",
|
||||
new ConfigOptionStrings({"Direct Drive TPU High Flow", "Direct Drive TPU High Flow"}));
|
||||
config.set_key_value("change_filament_gcode", new ConfigOptionString(
|
||||
"; VARIANT old={old_extruder_variant} new={new_extruder_variant}\nT[next_filament_id]\n"));
|
||||
|
||||
WHEN("the print is sliced") {
|
||||
const std::string gcode = slice_two_object_bbl(config);
|
||||
THEN("both placeholders resolve to the printer_extruder_variant value") {
|
||||
// The resolved line is the proof: an unresolved token or a parser throw would
|
||||
// prevent this exact line from being emitted. (A negative "{token}" check is
|
||||
// unreliable — the g-code's trailing config dump echoes the raw template.)
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring(
|
||||
"; VARIANT old=Direct Drive TPU High Flow new=Direct Drive TPU High Flow"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Global current-tool placeholders resolve in a context with no local injection", "[GCodeWriter][H2C]")
|
||||
{
|
||||
GIVEN("a BBL dual-extruder print whose before_layer_change_gcode reads the current-tool placeholders") {
|
||||
DynamicPrintConfig config = dual_extruder_toolchange_config();
|
||||
// before_layer_change is one of the contexts that inject NO current_* into their local config
|
||||
// (unlike change_filament / machine_end / layer_change), so these placeholders can only resolve
|
||||
// through the GLOBAL parser vars published at each toolchange (and at the initial set_extruder).
|
||||
// Pre-fix current_filament_id / current_extruder_id / current_nozzle_id were undefined here and the
|
||||
// whole slice threw a PlaceholderParserError — the same failure mode X2D's layer_change hit.
|
||||
config.set_key_value("before_layer_change_gcode", new ConfigOptionString(
|
||||
"; GVAR fid={current_filament_id} eid={current_extruder_id} nid={current_nozzle_id}\n"));
|
||||
|
||||
WHEN("the print is sliced (obj1 on filament 0, obj2 on filament 1)") {
|
||||
std::string gcode;
|
||||
REQUIRE_NOTHROW(gcode = slice_two_object_bbl(config));
|
||||
THEN("all three globals resolve to the CORRECT active-tool values on both sides of the change") {
|
||||
// Assert the FULL resolved marker, not just no-throw: obj1 prints on filament 0 (extruder 0,
|
||||
// nozzle 0) and obj2 on filament 1 (extruder 1, nozzle 1). Locking every field means a
|
||||
// stale or wrong global (e.g. obj2 still reading fid=0, or a mismatched extruder/nozzle id)
|
||||
// fails here — this is the value guard that replaces the old "throws on undefined" canary.
|
||||
// Only the emitted before_layer_change lines carry resolved values; the trailing config dump
|
||||
// keeps the raw "{current_filament_id}" template, so these are unambiguous.
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring("; GVAR fid=0 eid=0 nid=0"));
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring("; GVAR fid=1 eid=1 nid=1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("Shipped dual-nozzle change_filament_gcode resolves during a real slice", "[GCodeWriter][H2C][Profiles]")
|
||||
{
|
||||
const std::string printer = GENERATE(std::string("H2C"), std::string("H2D"), std::string("H2D Pro"), std::string("X2D"));
|
||||
|
||||
GIVEN("the real " + printer + " change_filament_gcode driving a BBL dual-extruder slice") {
|
||||
DynamicPrintConfig config = dual_extruder_toolchange_config();
|
||||
config.set_key_value("change_filament_gcode", new ConfigOptionString(shipped_change_filament_gcode(printer)));
|
||||
// H2D's gcode branches on the extruder variant; give the extruders distinct kits so the
|
||||
// "Direct Drive TPU High Flow" branch is reachable.
|
||||
config.set_key_value("printer_extruder_variant",
|
||||
new ConfigOptionStrings({"Direct Drive Standard", "Direct Drive TPU High Flow"}));
|
||||
// Extruder-indexed machine rates the stock gcode divides by (default size 1); size to 2 extruders.
|
||||
config.set_key_value("hotend_cooling_rate", new ConfigOptionFloatsNullable({2.0, 2.0}));
|
||||
config.set_key_value("hotend_heating_rate", new ConfigOptionFloatsNullable({2.0, 2.0}));
|
||||
|
||||
THEN("every placeholder resolves (no undefined-variable throw) and the change block runs") {
|
||||
std::string gcode;
|
||||
REQUIRE_NOTHROW(gcode = slice_two_object_bbl(config));
|
||||
// A resolved marker only the emitted change block produces (the trailing config
|
||||
// dump keeps the raw "{filament_type[...]}" template), so this confirms the real
|
||||
// change_filament_gcode was expanded, not merely echoed.
|
||||
REQUIRE_THAT(gcode, Catch::Matchers::ContainsSubstring("set_filament_type:PLA"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Custom G-code motion limits are restored before generated moves", "[GCodeWriter]")
|
||||
{
|
||||
const std::string gcode = Slic3r::Test::slice({ cube(20) }, {
|
||||
{ "gcode_flavor", "marlin" },
|
||||
{ "gcode_comments", "1" },
|
||||
{ "machine_start_gcode", "" },
|
||||
{ "layer_change_gcode", "M204 S5000\nm205 x5 y5\n" },
|
||||
{ "layer_height", "0.2" },
|
||||
{ "initial_layer_print_height", "0.2" },
|
||||
{ "initial_layer_line_width", "0" },
|
||||
{ "z_hop", "0" },
|
||||
{ "default_acceleration", "6000" },
|
||||
{ "initial_layer_acceleration", "6000" },
|
||||
{ "outer_wall_acceleration", "6000" },
|
||||
{ "inner_wall_acceleration", "0" },
|
||||
{ "default_jerk", "8" },
|
||||
{ "initial_layer_jerk", "8" },
|
||||
{ "outer_wall_jerk", "8" },
|
||||
{ "inner_wall_jerk", "0" },
|
||||
});
|
||||
|
||||
const size_t custom_gcode_pos = gcode.find("m205 x5 y5");
|
||||
REQUIRE(custom_gcode_pos != std::string::npos);
|
||||
REQUIRE(gcode.find("M204 S6000 ; adjust acceleration", custom_gcode_pos) != std::string::npos);
|
||||
REQUIRE(gcode.find("M205 X8 Y8 ; adjust jerk", custom_gcode_pos) != std::string::npos);
|
||||
}
|
||||
|
||||
@@ -399,6 +399,26 @@ std::string slice_two_cubes_apart(double gap, std::initializer_list<Slic3r::Conf
|
||||
return gcode(print);
|
||||
}
|
||||
|
||||
void place_two_cube_instances_apart(double gap, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items,
|
||||
Print &print, Model &model)
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict(config_items);
|
||||
config.set_key_value("gcode_comments", new ConfigOptionBool(true));
|
||||
|
||||
ModelObject *object = model.add_object();
|
||||
object->name += "object.stl";
|
||||
object->add_volume(cube(20));
|
||||
object->add_instance()->set_offset(Vec3d(80, 80, 0));
|
||||
object->add_instance()->set_offset(Vec3d(80 + 20 + gap, 80, 0));
|
||||
object->ensure_on_bed();
|
||||
print.auto_assign_extruders(object);
|
||||
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
}
|
||||
|
||||
std::set<double> layers_with_role(const std::string &gcode, const std::string &role)
|
||||
{
|
||||
std::set<double> layers;
|
||||
|
||||
@@ -108,6 +108,10 @@ void place_two_cubes_apart(double gap, std::initializer_list<Slic3r::ConfigBase:
|
||||
// Slice two 20mm cubes `gap` mm apart (not auto-arranged) and return the G-code.
|
||||
std::string slice_two_cubes_apart(double gap, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items);
|
||||
|
||||
// Place two instances of one 20mm cube `gap` mm apart edge-to-edge.
|
||||
void place_two_cube_instances_apart(double gap, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items,
|
||||
Slic3r::Print &print, Slic3r::Model &model);
|
||||
|
||||
// Distinct layer Z heights carrying an extrusion of the given `role` (e.g. "skirt").
|
||||
std::set<double> layers_with_role(const std::string &gcode, const std::string &role);
|
||||
|
||||
|
||||
@@ -85,3 +85,22 @@ TEST_CASE("Per-object wall filament override is honored", "[MultiFilament]")
|
||||
CHECK(tools_for_role(gcode, "perimeter") == std::set<int>{ 0, 1 });
|
||||
CHECK(tools_for_role(gcode, "infill") == std::set<int>{ 0 }); // infill not overridden: stays on F1
|
||||
}
|
||||
|
||||
// max_layer_height can be shorter than the extruder count (normalization sizes it to the
|
||||
// filament count under single_extruder_multi_material). calc_max_layer_height() in ToolOrdering
|
||||
// indexed it per-nozzle and read past the end. Shortened directly here to isolate that read;
|
||||
// the other per-extruder keys stay extruder-length so slicing reaches the code under test.
|
||||
TEST_CASE("Multi-extruder slice stays in bounds with a short max_layer_height", "[MultiFilament]")
|
||||
{
|
||||
DynamicPrintConfig config = multifilament_config(2);
|
||||
config.set_deserialize_strict({
|
||||
{ "nozzle_diameter", "0.4,0.4" },
|
||||
{ "printer_extruder_id", "1,2" },
|
||||
{ "printer_extruder_variant", "Direct Drive Standard,Direct Drive Standard" },
|
||||
{ "extruder_printable_height", "0,0" },
|
||||
{ "max_layer_height", "0.3" }, // deliberately one entry short
|
||||
});
|
||||
Print print;
|
||||
init_and_process_print({ cube(20) }, print, config);
|
||||
REQUIRE_FALSE(print.objects().front()->layers().empty());
|
||||
}
|
||||
|
||||
@@ -418,3 +418,25 @@ TEST_CASE("Sequential printing follows model order", "[Print]")
|
||||
|
||||
REQUIRE_THAT(first_object_peak_z, Catch::Matchers::WithinAbs(20.0, 0.3));
|
||||
}
|
||||
|
||||
// A sequential (by-object) print must publish the print-level nozzle group result just
|
||||
// like a by-layer print, so custom g-code can index the per-nozzle placeholder tables
|
||||
// (e.g. nozzle_diameter_at_nozzle_id[]) instead of failing on an empty vector.
|
||||
TEST_CASE("Sequential printing publishes the nozzle group result", "[Print][MultiNozzle]")
|
||||
{
|
||||
SECTION("process() publishes the result") {
|
||||
Print print;
|
||||
Model model;
|
||||
place_two_cubes_apart(60.0, { { "print_sequence", "by object" } }, print, model);
|
||||
print.process();
|
||||
REQUIRE(print.get_layered_nozzle_group_result() != nullptr);
|
||||
}
|
||||
|
||||
SECTION("start g-code can index the per-nozzle diameter table") {
|
||||
const std::string gcode = slice_two_cubes_arranged({
|
||||
{ "print_sequence", "by object" },
|
||||
{ "machine_start_gcode", "{if nozzle_diameter_at_nozzle_id[0] > 0}; SEQ-ND-OK\n{endif}" },
|
||||
});
|
||||
CHECK(gcode.find("; SEQ-ND-OK") != std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,27 @@ TEST_CASE("Per-object skirts group when objects are close", "[SkirtBrim]")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Per-object skirt is generated per instance", "[SkirtBrim]")
|
||||
{
|
||||
Print print;
|
||||
Model model;
|
||||
place_two_cube_instances_apart(60, {
|
||||
{ "skirt_type", "perobject" },
|
||||
{ "skirt_height", 1 },
|
||||
{ "skirt_distance", 2 },
|
||||
{ "skirt_loops", 1 },
|
||||
{ "brim_type", "no_brim" },
|
||||
}, print, model);
|
||||
print.process();
|
||||
|
||||
REQUIRE(print.skirt_brim_groups().size() == 2);
|
||||
REQUIRE(print.skirt().items_count() == 2);
|
||||
for (const Print::SkirtBrimGroup &group : print.skirt_brim_groups()) {
|
||||
REQUIRE(group.instances.size() == 1);
|
||||
REQUIRE(group.instances.front().object_id == print.get_object(0)->id());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Combine brims merges touching brims", "[SkirtBrim]")
|
||||
{
|
||||
auto [gap, combine, expected_brims] = GENERATE(table<double, int, int>({
|
||||
@@ -112,6 +133,45 @@ TEST_CASE("Combine brims merges touching brims", "[SkirtBrim]")
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Object brims are generated per instance", "[SkirtBrim]")
|
||||
{
|
||||
Print print;
|
||||
Model model;
|
||||
place_two_cube_instances_apart(60, {
|
||||
{ "skirt_loops", 0 },
|
||||
{ "brim_type", "outer_only" },
|
||||
{ "brim_width", 5 },
|
||||
{ "combine_brims", 0 },
|
||||
}, print, model);
|
||||
print.process();
|
||||
|
||||
REQUIRE(print.skirt_brim_groups().size() == 1);
|
||||
REQUIRE(print.skirt_brim_groups().front().brims.size() == 2);
|
||||
for (const Print::SkirtBrimGroup::Brim &brim : print.skirt_brim_groups().front().brims) {
|
||||
REQUIRE(brim.instances.size() == 1);
|
||||
REQUIRE(brim.instances.front().object_id == print.get_object(0)->id());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Combine brims merges neighboring object instances", "[SkirtBrim]")
|
||||
{
|
||||
Print print;
|
||||
Model model;
|
||||
place_two_cube_instances_apart(5, {
|
||||
{ "skirt_loops", 0 },
|
||||
{ "brim_type", "outer_only" },
|
||||
{ "brim_width", 5 },
|
||||
{ "combine_brims", 1 },
|
||||
}, print, model);
|
||||
print.process();
|
||||
|
||||
REQUIRE(print.skirt_brim_groups().size() == 1);
|
||||
REQUIRE(print.skirt_brim_groups().front().brims.size() == 1);
|
||||
REQUIRE(print.skirt_brim_groups().front().brims.front().instances.size() == 2);
|
||||
const std::vector<std::string> expected{ "brim", "perimeter" };
|
||||
CHECK(role_sequence(gcode(print), { "brim", "perimeter" }) == expected);
|
||||
}
|
||||
|
||||
// Each object's skirt and brim come right before that object, not all skirts then all brims first.
|
||||
TEST_CASE("By-layer per-object skirt and brim precede each object", "[SkirtBrim]")
|
||||
{
|
||||
|
||||
559
tests/fff_print/test_slicing_pipeline_hook.cpp
Normal file
559
tests/fff_print/test_slicing_pipeline_hook.cpp
Normal file
@@ -0,0 +1,559 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "test_helpers.hpp"
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("slicing_pipeline_plugin option exists and defaults empty", "[slicing_pipeline]") {
|
||||
DynamicPrintConfig cfg = DynamicPrintConfig::full_print_config();
|
||||
const ConfigOptionStrings* opt = cfg.option<ConfigOptionStrings>("slicing_pipeline_plugin");
|
||||
REQUIRE(opt != nullptr);
|
||||
CHECK(opt->values.empty());
|
||||
const ConfigOptionDef* def = cfg.def()->get("slicing_pipeline_plugin");
|
||||
REQUIRE(def != nullptr);
|
||||
CHECK(def->plugin_type == "slicing-pipeline");
|
||||
CHECK(def->is_plugin_backed());
|
||||
CHECK(def->gui_type == ConfigOptionDef::GUIType::plugin_picker);
|
||||
}
|
||||
|
||||
#include "libslic3r/Print.hpp"
|
||||
|
||||
TEST_CASE("slicing pipeline hook setter is a no-op-safe injection", "[slicing_pipeline]") {
|
||||
int calls = 0;
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[&](Slic3r::Print&, const Slic3r::PrintObject*, Slic3r::SlicingPipelineStepPlugin){ ++calls; });
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr); // reset — must be legal
|
||||
CHECK(calls == 0);
|
||||
}
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
using namespace Slic3r::Test;
|
||||
|
||||
TEST_CASE("SlicingPipeline hook fires once per step per object in order", "[slicing_pipeline]") {
|
||||
struct Call { const Slic3r::PrintObject* obj; Slic3r::SlicingPipelineStepPlugin step; };
|
||||
std::vector<Call> calls;
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[&](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){ calls.push_back({o, s}); });
|
||||
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
Slic3r::DynamicPrintConfig config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"})); // activate
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
|
||||
using S = Slic3r::SlicingPipelineStepPlugin;
|
||||
auto count = [&](S s){ return std::count_if(calls.begin(), calls.end(), [&](const Call& c){ return c.step == s; }); };
|
||||
CHECK(count(S::posSlice) == 1);
|
||||
CHECK(count(S::posPerimeters) == 1);
|
||||
CHECK(count(S::posPrepareInfill) == 1); // the prepare-infill seam fires once per object
|
||||
CHECK(count(S::posInfill) == 1);
|
||||
CHECK(count(S::psWipeTower) == 1);
|
||||
CHECK(count(S::psSkirtBrim) == 1);
|
||||
// psGCodePostProcess fires from the GUI export path, never from process():
|
||||
CHECK(count(S::psGCodePostProcess) == 0);
|
||||
// print-wide steps carry a null object:
|
||||
for (const auto& c : calls)
|
||||
if (c.step == S::psWipeTower || c.step == S::psSkirtBrim) CHECK(c.obj == nullptr);
|
||||
// Slice must fire before Perimeters for the same object:
|
||||
auto idx = [&](S s){ for (size_t i=0;i<calls.size();++i) if (calls[i].step==s) return (int)i; return -1; };
|
||||
CHECK(idx(S::posSlice) < idx(S::posPerimeters));
|
||||
CHECK(idx(S::posPerimeters) < idx(S::posPrepareInfill)); // prepare-infill fires after perimeters...
|
||||
CHECK(idx(S::posPrepareInfill) < idx(S::posInfill)); // ...and before the fills are built
|
||||
}
|
||||
|
||||
#include <sstream>
|
||||
#include <cmath>
|
||||
|
||||
// Exported G-code carries a few nondeterministic comment lines unrelated to toolpaths: a
|
||||
// wall-clock timestamp ("; generated by ..."), ObjectID-derived ids (from a process-global
|
||||
// counter never reset between runs), and a config-dump line naming the selected plugin (an
|
||||
// active run records it, the absent baseline does not). Strip exactly those lines so a raw
|
||||
// byte-compare isolates the real motion/extrusion output; every other byte is still compared.
|
||||
static std::string strip_nondeterministic_gcode_lines(const std::string& gcode) {
|
||||
std::string out; out.reserve(gcode.size());
|
||||
std::istringstream in(gcode);
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
if (line.compare(0, 15, "; generated by ") == 0) continue; // wall-clock timestamp
|
||||
if (line.compare(0, 18, "; model label id: ") == 0) continue; // ObjectID-derived
|
||||
// "; [stop] printing object <name> id:N copy M" / "... unique label id: N" (ObjectID-derived):
|
||||
if (line.find("printing object") != std::string::npos && line.find(" id:") != std::string::npos) continue;
|
||||
if (line.find("slicing_pipeline_plugin") != std::string::npos) continue; // config-dump plugin name
|
||||
out += line; out += '\n';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
TEST_CASE("Inactive hook: process output is byte-identical (no-op hook == unset)", "[slicing_pipeline]") {
|
||||
// Three configurations must all normalize to the same G-code:
|
||||
// (activate=false, hook=none) baseline -- feature entirely absent.
|
||||
// (activate=false, hook=noop) hook registered but option empty -> gated off, never fires.
|
||||
// (activate=true, hook=noop) hook ACTIVE and firing at every pipeline seam, mutating
|
||||
// nothing. This is the real backward-compat claim: an active
|
||||
// but non-mutating hook must not perturb the output.
|
||||
auto run = [](bool activate, bool set_noop_hook) {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
// Activating requires BOTH a non-empty option and a registered hook (see Print::apply).
|
||||
if (activate)
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
if (set_noop_hook)
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn([](Slic3r::Print&, const Slic3r::PrintObject*, Slic3r::SlicingPipelineStepPlugin){});
|
||||
else
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
init_print({cube(20)}, print, model, config);
|
||||
std::string g = Slic3r::Test::gcode(print);
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return g;
|
||||
};
|
||||
// Compare only machine-meaningful output (see strip_nondeterministic_gcode_lines): every
|
||||
// motion/extrusion byte is still compared, so this proves the inactive hook -- and the
|
||||
// active-but-non-mutating hook -- leave the real toolpath byte-identical.
|
||||
const std::string baseline = strip_nondeterministic_gcode_lines(run(false, false)); // feature absent
|
||||
CHECK(strip_nondeterministic_gcode_lines(run(false, true)) == baseline); // gated off: hook never fires
|
||||
CHECK(strip_nondeterministic_gcode_lines(run(true, true)) == baseline); // active no-op hook fires everywhere, mutates nothing
|
||||
}
|
||||
|
||||
// Gating negative path. With the option EMPTY the plugin is inactive, so a
|
||||
// registered hook must NOT fire even once across a full slice (m_pipeline_plugin_active
|
||||
// stays false in Print::apply). Distinct from the byte-identical test above: this asserts
|
||||
// the gate directly by counting invocations rather than comparing output.
|
||||
TEST_CASE("Empty option: registered hook is gated off and never fires", "[slicing_pipeline]") {
|
||||
int calls = 0;
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[&](Slic3r::Print&, const Slic3r::PrintObject*, Slic3r::SlicingPipelineStepPlugin){ ++calls; });
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
// option left EMPTY -> inactive regardless of the registered hook.
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
CHECK(calls == 0);
|
||||
}
|
||||
|
||||
// Duplicate-skip gating. Two ModelObjects that share one mesh_ptr are detected as
|
||||
// identical by Print::process()'s is_print_object_the_same(); the second becomes a shared
|
||||
// (duplicate) object and is NOT re-sliced, so the Slice hook must fire exactly once even
|
||||
// though there are two print objects. The clone shares mesh_ptr and copies the volume
|
||||
// transformation/config (ModelVolume copy ctor), which the equality check requires.
|
||||
TEST_CASE("Duplicate objects share a slice: Slice hook fires exactly once", "[slicing_pipeline]") {
|
||||
int slice_calls = 0, perim_calls = 0;
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[&](Slic3r::Print&, const Slic3r::PrintObject*, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s == Slic3r::SlicingPipelineStepPlugin::posSlice) ++slice_calls;
|
||||
if (s == Slic3r::SlicingPipelineStepPlugin::posPerimeters) ++perim_calls;
|
||||
});
|
||||
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"})); // activate
|
||||
|
||||
// init_print builds one arranged, on-bed cube object (o1).
|
||||
init_print({cube(20)}, print, model, config);
|
||||
Slic3r::ModelObject* o1 = model.objects.front();
|
||||
// Model::add_object(const ModelObject&) force-sets object extruder=1 on the clone; give o1
|
||||
// the same so the two objects' configs match (is_print_object_the_same compares config).
|
||||
if (!o1->config.has("extruder"))
|
||||
o1->config.set_key_value("extruder", new Slic3r::ConfigOptionInt(1));
|
||||
// Clone o1: shares mesh_ptr and copies the volume transformation + config (genuine duplicate).
|
||||
Slic3r::ModelObject* o2 = model.add_object(*o1);
|
||||
// Shift the clone in X so validate() sees no collision (20mm cubes -> 40mm centres = 20mm gap).
|
||||
for (Slic3r::ModelInstance* inst : o2->instances)
|
||||
inst->set_offset(inst->get_offset() + Slic3r::Vec3d(40.0, 0.0, 0.0));
|
||||
|
||||
print.apply(model, config);
|
||||
print.validate();
|
||||
print.set_status_silent();
|
||||
print.process();
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
|
||||
REQUIRE(print.objects().size() == 2); // two print objects present...
|
||||
CHECK(slice_calls == 1); // ...but the duplicate is skipped -> one slice
|
||||
CHECK(perim_calls == 1); // and one perimeters pass (the sliced object)
|
||||
}
|
||||
|
||||
#include "libslic3r/Layer.hpp" // Layer, LayerRegion (full defs for the cascade hook)
|
||||
#include "libslic3r/ClipperUtils.hpp" // offset_ex
|
||||
|
||||
// The correctness heart of the mutation feature. A C++ hook insets every
|
||||
// region's `slices` at the Slice boundary (via SurfaceCollection::set with offset
|
||||
// polygons); because make_perimeters() derives fill_surfaces from slices AFTER the
|
||||
// Slice hook fires (see Print::process's split slice loop), the downstream
|
||||
// fill_surfaces area must shrink relative to a baseline (un-inset) run. This proves
|
||||
// the mutation cascade end-to-end using the same C++ APIs the Python mutators wrap.
|
||||
TEST_CASE("Mutating slices at the Slice boundary cascades downstream", "[slicing_pipeline]") {
|
||||
auto fill_area = [](bool inset) {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
if (inset) Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces;
|
||||
for (auto& sf : in) sf.expolygon = offset_ex(sf.expolygon, -scale_(1.0)).front();
|
||||
r->slices.set(std::move(in));
|
||||
}
|
||||
});
|
||||
else Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
double a = 0; for (auto* l : print.objects().front()->layers()) for (auto* r : l->regions()) for (auto& s : r->fill_surfaces.surfaces) a += s.expolygon.area();
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return a;
|
||||
};
|
||||
CHECK(fill_area(true) < fill_area(false));
|
||||
}
|
||||
|
||||
TEST_CASE("Changing slicing_pipeline_plugin invalidates posSlice", "[slicing_pipeline]") {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
REQUIRE(print.objects().front()->is_step_done(posSlice));
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
print.apply(model, config);
|
||||
CHECK_FALSE(print.objects().front()->is_step_done(posSlice)); // re-slice required
|
||||
}
|
||||
|
||||
#include <catch2/matchers/catch_matchers_floating_point.hpp>
|
||||
|
||||
// A similarity transform (rotate + uniform scale) applied to slices at Step.posSlice, matching
|
||||
// what the Twistify sample (sandboxes/orca_twistify_plugin_example_any.py) does. This C++ analogue
|
||||
// rotates every region's slices a fixed 45 deg about the object's base-footprint center -- the same
|
||||
// seam and cascade the sample drives through the slices.set() + Layer::make_slices() path. Two
|
||||
// end-to-end invariants after process() confirm the approach:
|
||||
// (1) a pure rotation is a similarity with scale 1, so total fill area is preserved, and
|
||||
// (2) the mutation genuinely cascaded into make_perimeters' fill_surfaces -- a 20mm square
|
||||
// rotated 45 deg becomes a diamond whose bbox is ~sqrt(2)x wider (it did not stay
|
||||
// axis-aligned), proving downstream geometry was rebuilt from the twisted slices.
|
||||
TEST_CASE("Rotating slices at the Slice boundary cascades (area preserved, bbox rotated)", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
struct Measure { double area; double width; double height; };
|
||||
auto measure = [](bool rotate) -> Measure {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
if (rotate) Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
auto* obj = const_cast<Slic3r::PrintObject*>(o);
|
||||
// Twist axis = center of the first sliced layer's footprint (Twistify's anchor).
|
||||
coord_t nx=0, xx=0, ny=0, xy=0; bool seeded=false;
|
||||
for (Slic3r::Layer* l : obj->layers()) {
|
||||
for (Slic3r::LayerRegion* r : l->regions())
|
||||
for (const Slic3r::Surface& sf : r->slices.surfaces)
|
||||
for (const Slic3r::Point& p : sf.expolygon.contour.points) {
|
||||
if (!seeded) { nx=xx=p.x(); ny=xy=p.y(); seeded=true; }
|
||||
else { nx=std::min(nx,p.x()); xx=std::max(xx,p.x());
|
||||
ny=std::min(ny,p.y()); xy=std::max(xy,p.y()); }
|
||||
}
|
||||
if (seeded) break;
|
||||
}
|
||||
const double cx = 0.5*((double)nx+(double)xx), cy = 0.5*((double)ny+(double)xy);
|
||||
const double ct = 0.7071067811865476, st = 0.7071067811865476; // cos/sin 45 deg
|
||||
auto rot = [&](const Slic3r::Point& p) {
|
||||
const double dx = (double)p.x()-cx, dy = (double)p.y()-cy;
|
||||
return Slic3r::Point((coord_t)std::llround(dx*ct - dy*st + cx),
|
||||
(coord_t)std::llround(dx*st + dy*ct + cy));
|
||||
};
|
||||
for (Slic3r::Layer* l : obj->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces;
|
||||
for (auto& sf : in) {
|
||||
for (auto& pt : sf.expolygon.contour.points) pt = rot(pt);
|
||||
for (auto& h : sf.expolygon.holes)
|
||||
for (auto& pt : h.points) pt = rot(pt);
|
||||
}
|
||||
r->slices.set(std::move(in));
|
||||
}
|
||||
});
|
||||
else Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
double area = 0;
|
||||
coord_t nx=0, xx=0, ny=0, xy=0; bool seeded=false;
|
||||
for (auto* l : print.objects().front()->layers())
|
||||
for (auto* r : l->regions())
|
||||
for (auto& sf : r->fill_surfaces.surfaces) {
|
||||
area += sf.expolygon.area();
|
||||
for (const Slic3r::Point& p : sf.expolygon.contour.points) {
|
||||
if (!seeded) { nx=xx=p.x(); ny=xy=p.y(); seeded=true; }
|
||||
else { nx=std::min(nx,p.x()); xx=std::max(xx,p.x());
|
||||
ny=std::min(ny,p.y()); xy=std::max(xy,p.y()); }
|
||||
}
|
||||
}
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return { area, (double)(xx-nx), (double)(xy-ny) };
|
||||
};
|
||||
const Measure base = measure(false);
|
||||
const Measure rot = measure(true);
|
||||
// (1) A pure rotation preserves area (similarity, scale 1): fills add up to the same area.
|
||||
CHECK_THAT(rot.area, WithinRel(base.area, 0.05));
|
||||
// (2) The rotation cascaded downstream: the square's fill bbox grew toward the sqrt(2)
|
||||
// diagonal (diamond) instead of staying axis-aligned.
|
||||
CHECK(rot.width > 1.3 * base.width);
|
||||
CHECK(rot.width < 1.5 * base.width);
|
||||
CHECK(rot.height > 1.3 * base.height);
|
||||
CHECK(rot.height < 1.5 * base.height);
|
||||
}
|
||||
|
||||
// The Twistify sample skips exact-identity layers entirely, but every transformed layer invokes
|
||||
// the slices.set() write-back + make_perimeters re-run. This proves that write path is lossless
|
||||
// for already-normalized (CCW contour / CW hole) input -- an active hook that re-sets every
|
||||
// region's slices to their CURRENT geometry (the identity similarity transform) produces output
|
||||
// byte-identical to an active hook that mutates nothing. Both runs are active (same config dump);
|
||||
// the only difference is whether the write path ran, so equality isolates it.
|
||||
TEST_CASE("Identity round-trip through slices.set() is byte-identical", "[slicing_pipeline]") {
|
||||
auto run = [](bool roundtrip) {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"})); // active in both runs
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[roundtrip](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (!roundtrip || s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces; // copy current (already-normalized) geometry
|
||||
r->slices.set(std::move(in)); // write back unchanged: identity transform
|
||||
}
|
||||
});
|
||||
init_print({cube(20)}, print, model, config);
|
||||
std::string g = Slic3r::Test::gcode(print);
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return g;
|
||||
};
|
||||
CHECK(strip_nondeterministic_gcode_lines(run(true)) == strip_nondeterministic_gcode_lines(run(false)));
|
||||
}
|
||||
|
||||
#include "libslic3r/ExtrusionEntityCollection.hpp" // count fill paths in the fill-surface cascade test
|
||||
|
||||
// Total leaf ExtrusionPath count under an extrusion (sub)tree (collections recursed into).
|
||||
static size_t count_leaf_paths(const Slic3r::ExtrusionEntity* ee) {
|
||||
if (ee == nullptr) return 0;
|
||||
if (const auto* coll = dynamic_cast<const Slic3r::ExtrusionEntityCollection*>(ee)) {
|
||||
size_t n = 0;
|
||||
for (const Slic3r::ExtrusionEntity* e : coll->entities) n += count_leaf_paths(e);
|
||||
return n;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Width (scaled) of the object-wide bounding box over every region's sliced contour.
|
||||
static double outer_slices_width(const Slic3r::Print& print) {
|
||||
coord_t min_x = 0, max_x = 0; bool seeded = false;
|
||||
for (auto* l : print.objects().front()->layers())
|
||||
for (auto* r : l->regions())
|
||||
for (const Slic3r::Surface& sf : r->slices.surfaces)
|
||||
for (const Slic3r::Point& p : sf.expolygon.contour.points) {
|
||||
if (!seeded) { min_x = max_x = p.x(); seeded = true; }
|
||||
else { min_x = std::min(min_x, p.x()); max_x = std::max(max_x, p.x()); }
|
||||
}
|
||||
return (double)(max_x - min_x);
|
||||
}
|
||||
|
||||
// After the Slice hook mutates slices, raw_slices must be re-snapshotted so the mutation
|
||||
// becomes the untyped baseline. make_perimeters() restores untyped slices from raw_slices on
|
||||
// any perimeter re-run; invoking that restore directly must reproduce the mutation, not revert
|
||||
// to the pre-hook geometry (which is what happened before this fix).
|
||||
TEST_CASE("raw_slices captures post-hook geometry so a perimeter re-run keeps the mutation", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces;
|
||||
for (auto& sf : in) {
|
||||
Slic3r::ExPolygons e = offset_ex(sf.expolygon, -scale_(1.0));
|
||||
if (!e.empty()) sf.expolygon = e.front();
|
||||
}
|
||||
r->slices.set(std::move(in));
|
||||
}
|
||||
});
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
const double w_mutated = outer_slices_width(print); // inset applied at the Slice hook
|
||||
|
||||
// The same restore make_perimeters() runs on a perimeter-only re-slice. With the post-hook
|
||||
// backup this reproduces the inset; without it this reverts to the wider original outline.
|
||||
for (Slic3r::Layer* l : print.objects().front()->layers())
|
||||
l->restore_untyped_slices();
|
||||
const double w_restored = outer_slices_width(print);
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
CHECK_THAT(w_restored, WithinRel(w_mutated, 0.02)); // mutation survived the restore
|
||||
}
|
||||
|
||||
// A plugin can mutate fill_surfaces at the new PrepareInfill seam and have make_fills consume
|
||||
// them, whereas the pre-existing Infill seam fires after the fills are already built.
|
||||
// All three runs register a hook (active path) so the comparison isolates only the mutation.
|
||||
TEST_CASE("fill_surfaces mutation cascades at PrepareInfill but not at Infill", "[slicing_pipeline]") {
|
||||
auto fill_paths = [](bool shrink, Slic3r::SlicingPipelineStepPlugin at) {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[shrink, at](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (!shrink || s != at || !o) return;
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->fill_surfaces.surfaces, out;
|
||||
for (const Slic3r::Surface& sf : in)
|
||||
for (const Slic3r::ExPolygon& e : offset_ex(sf.expolygon, -scale_(3.0))) {
|
||||
Slic3r::Surface s2 = sf; s2.expolygon = e; out.push_back(std::move(s2));
|
||||
}
|
||||
r->fill_surfaces.set(std::move(out));
|
||||
}
|
||||
});
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
size_t n = 0;
|
||||
for (auto* l : print.objects().front()->layers())
|
||||
for (auto* r : l->regions())
|
||||
n += count_leaf_paths(&r->fills);
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return n;
|
||||
};
|
||||
using S = Slic3r::SlicingPipelineStepPlugin;
|
||||
const size_t base = fill_paths(false, S::posPrepareInfill); // active hook, no mutation
|
||||
CHECK(base > 0);
|
||||
CHECK(fill_paths(true, S::posPrepareInfill) < base); // mutation before make_fills cascades
|
||||
CHECK(fill_paths(true, S::posInfill) == base); // mutation after make_fills is a no-op
|
||||
}
|
||||
|
||||
// lslices (the layer's merged islands) are built once in slice() and never rebuilt by
|
||||
// make_perimeters, so mutating region slices leaves them stale. The slices.set() + Layer::make_slices()
|
||||
// path re-derives them; this C++ analogue proves the mechanism -- without the
|
||||
// refresh the islands keep the original 20mm footprint, with it they track the 18mm inset.
|
||||
TEST_CASE("refreshing lslices after a slice mutation makes islands track the geometry", "[slicing_pipeline]") {
|
||||
auto lslices_width = [](bool refresh) {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"}));
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[refresh](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers()) {
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces;
|
||||
for (auto& sf : in) {
|
||||
Slic3r::ExPolygons e = offset_ex(sf.expolygon, -scale_(1.0));
|
||||
if (!e.empty()) sf.expolygon = e.front();
|
||||
}
|
||||
r->slices.set(std::move(in));
|
||||
}
|
||||
if (refresh) // the load-bearing half of the slices.set() + Layer::make_slices() path
|
||||
l->make_slices();
|
||||
}
|
||||
});
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
coord_t min_x = 0, max_x = 0; bool seeded = false;
|
||||
for (auto* l : print.objects().front()->layers())
|
||||
for (const Slic3r::ExPolygon& island : l->lslices)
|
||||
for (const Slic3r::Point& p : island.contour.points) {
|
||||
if (!seeded) { min_x = max_x = p.x(); seeded = true; }
|
||||
else { min_x = std::min(min_x, p.x()); max_x = std::max(max_x, p.x()); }
|
||||
}
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return (double)(max_x - min_x);
|
||||
};
|
||||
using Catch::Matchers::WithinRel;
|
||||
const double stale = lslices_width(false); // islands keep the original ~20 mm footprint
|
||||
const double fresh = lslices_width(true); // islands track the ~18 mm inset region slices
|
||||
CHECK(fresh < stale);
|
||||
CHECK_THAT(stale, WithinRel((double) scale_(20.0), 0.05)); // stale islands = original outline
|
||||
CHECK_THAT(fresh, WithinRel((double) scale_(18.0), 0.05)); // refreshed islands = inset outline
|
||||
}
|
||||
|
||||
#include <random> // deterministic RNG for the fuzzy-skin analogue below
|
||||
|
||||
// Fuzzy skin applied to the slice contours at the Slice boundary, matching what the Fuzzy
|
||||
// Slices sample (sandboxes/orca_fuzzy_slices_plugin_any.py) does: resample every ring at
|
||||
// 3/4..5/4 * point_distance and displace each new vertex +/-thickness along the segment
|
||||
// normal (libslic3r's fuzzy_polyline with uniform noise). Unlike the count-preserving rotate
|
||||
// test above, this is a count-CHANGING rebuild -- each ring is replaced by one with a
|
||||
// different vertex count. Three end-to-end invariants after process() confirm the cascade:
|
||||
// (1) the jitter is zero-mean, so total fill area is preserved within a few %,
|
||||
// (2) the fuzz genuinely cascaded into make_perimeters' fill_surfaces -- their contours
|
||||
// carry far more vertices than the crisp baseline square's,
|
||||
// (3) displacement is bounded: the sliced footprint grows by at most ~2*thickness.
|
||||
TEST_CASE("Fuzzing slice contours at the Slice boundary cascades with bounded displacement", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
static constexpr double kThickness = 0.3, kPointDist = 0.8; // mm; the built-in fuzzy-skin defaults
|
||||
struct Measure { double area; size_t verts; double width; };
|
||||
auto measure = [](bool fuzz) -> Measure {
|
||||
Slic3r::Print print; Slic3r::Model model;
|
||||
auto config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new Slic3r::ConfigOptionStrings({"probe"})); // active in both runs
|
||||
if (fuzz) Slic3r::Print::set_slicing_pipeline_hook_fn(
|
||||
[](Slic3r::Print&, const Slic3r::PrintObject* o, Slic3r::SlicingPipelineStepPlugin s){
|
||||
if (s != Slic3r::SlicingPipelineStepPlugin::posSlice || !o) return;
|
||||
const double thickness = scale_(kThickness);
|
||||
const double min_dist = scale_(kPointDist) * 0.75;
|
||||
const double rand_range = scale_(kPointDist) * 0.5;
|
||||
std::mt19937 rng(0x5EED); // fixed seed: the run is deterministic
|
||||
std::uniform_real_distribution<double> uni(0.0, 1.0);
|
||||
auto fuzz_ring = [&](Slic3r::Points& pts) {
|
||||
if (pts.size() < 3) return;
|
||||
Slic3r::Points out;
|
||||
double dist_left_over = uni(rng) * (min_dist / 2.0);
|
||||
const Slic3r::Point* p0 = &pts.back();
|
||||
for (const Slic3r::Point& p1 : pts) {
|
||||
const Slic3r::Vec2d v = (p1 - *p0).cast<double>();
|
||||
const double seg = v.norm();
|
||||
if (seg > 0.0) {
|
||||
double d = dist_left_over;
|
||||
for (; d < seg; d += min_dist + uni(rng) * rand_range) {
|
||||
const double r = (uni(rng) * 2.0 - 1.0) * thickness;
|
||||
const Slic3r::Vec2d pa = p0->cast<double>() + v * (d / seg);
|
||||
const Slic3r::Vec2d n = Slic3r::Vec2d(-v.y(), v.x()) / seg;
|
||||
out.emplace_back((coord_t) std::llround(pa.x() + n.x() * r),
|
||||
(coord_t) std::llround(pa.y() + n.y() * r));
|
||||
}
|
||||
dist_left_over = d - seg;
|
||||
}
|
||||
p0 = &p1;
|
||||
}
|
||||
if (out.size() >= 3) pts = std::move(out); // else: ring too short, keep it crisp
|
||||
};
|
||||
for (Slic3r::Layer* l : const_cast<Slic3r::PrintObject*>(o)->layers())
|
||||
for (Slic3r::LayerRegion* r : l->regions()) {
|
||||
Slic3r::Surfaces in = r->slices.surfaces;
|
||||
for (auto& sf : in) {
|
||||
fuzz_ring(sf.expolygon.contour.points);
|
||||
for (auto& h : sf.expolygon.holes) fuzz_ring(h.points);
|
||||
}
|
||||
r->slices.set(std::move(in));
|
||||
}
|
||||
});
|
||||
else Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
Measure m { 0.0, 0, outer_slices_width(print) };
|
||||
for (auto* l : print.objects().front()->layers())
|
||||
for (auto* r : l->regions())
|
||||
for (auto& sf : r->fill_surfaces.surfaces) {
|
||||
m.area += sf.expolygon.area();
|
||||
m.verts += sf.expolygon.contour.points.size();
|
||||
}
|
||||
Slic3r::Print::set_slicing_pipeline_hook_fn(nullptr);
|
||||
return m;
|
||||
};
|
||||
const Measure base = measure(false);
|
||||
const Measure fz = measure(true);
|
||||
// (1) Zero-mean jitter: the fills add up to (nearly) the same area.
|
||||
CHECK_THAT(fz.area, WithinRel(base.area, 0.05));
|
||||
// (2) The resample cascaded downstream: fill boundaries derived from the fuzzed slices
|
||||
// carry far more vertices than the baseline square's.
|
||||
CHECK(fz.verts > 4 * base.verts);
|
||||
// (3) Displacement is bounded by the +/-thickness jitter: the footprint widened, but by
|
||||
// no more than ~2*thickness (one thickness per side, plus rounding slack).
|
||||
CHECK(fz.width > base.width);
|
||||
CHECK(fz.width < base.width + 2.5 * scale_(kThickness));
|
||||
}
|
||||
23
tests/filament_group/CMakeLists.txt
Normal file
23
tests/filament_group/CMakeLists.txt
Normal file
@@ -0,0 +1,23 @@
|
||||
get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME)
|
||||
|
||||
set(FG_GOLDEN_DIR ${CMAKE_CURRENT_SOURCE_DIR}/golden)
|
||||
file(TO_NATIVE_PATH "${FG_GOLDEN_DIR}" FG_GOLDEN_DIR)
|
||||
|
||||
add_executable(${_TEST_NAME}_tests
|
||||
filament_group_regression_main.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(${_TEST_NAME}_tests test_common libslic3r nlohmann_json Catch2::Catch2WithMain)
|
||||
# ${CMAKE_SOURCE_DIR}/deps_src puts <nlohmann/json.hpp> on the include path the same way the
|
||||
# libslic3r translation units resolve it (via the admesh/.. system include); nlohmann_json's own
|
||||
# interface dir only exposes <json.hpp>, so the source-tree include is required for the <nlohmann/…>
|
||||
# spelling the serializers use.
|
||||
target_include_directories(${_TEST_NAME}_tests PRIVATE ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/deps_src)
|
||||
target_compile_definitions(${_TEST_NAME}_tests PRIVATE
|
||||
FG_TEST_GOLDEN_DIR=R"\(${FG_GOLDEN_DIR}\)"
|
||||
)
|
||||
set_property(TARGET ${_TEST_NAME}_tests PROPERTY FOLDER "tests")
|
||||
|
||||
orcaslicer_copy_test_dlls()
|
||||
|
||||
orcaslicer_discover_tests(${_TEST_NAME}_tests)
|
||||
237
tests/filament_group/fg_test_evaluator.hpp
Normal file
237
tests/filament_group/fg_test_evaluator.hpp
Normal file
@@ -0,0 +1,237 @@
|
||||
#ifndef FG_TEST_EVALUATOR_HPP
|
||||
#define FG_TEST_EVALUATOR_HPP
|
||||
|
||||
#include "fg_test_serialization.hpp"
|
||||
#include <libslic3r/FilamentGroup.hpp>
|
||||
#include <libslic3r/GCode/ToolOrderUtils.hpp>
|
||||
#include <libslic3r/MultiNozzleUtils.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace Slic3r {
|
||||
namespace FGTest {
|
||||
|
||||
inline bool check_constraints(const FilamentGroupContext& ctx,
|
||||
const std::vector<int>& filament_map,
|
||||
std::vector<std::string>& violations) {
|
||||
violations.clear();
|
||||
auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments);
|
||||
|
||||
// 1. unprintable_filaments check
|
||||
for (size_t ext = 0; ext < ctx.model_info.unprintable_filaments.size(); ++ext) {
|
||||
for (int fil : ctx.model_info.unprintable_filaments[ext]) {
|
||||
if (fil < 0 || fil >= (int)filament_map.size())
|
||||
continue;
|
||||
int assigned_nozzle = filament_map[fil];
|
||||
if (assigned_nozzle < 0 || assigned_nozzle >= (int)ctx.nozzle_info.nozzle_list.size())
|
||||
continue;
|
||||
if (ctx.nozzle_info.nozzle_list[assigned_nozzle].extruder_id == (int)ext) {
|
||||
std::ostringstream ss;
|
||||
ss << "filament " << fil << " assigned to nozzle " << assigned_nozzle
|
||||
<< " (extruder " << ext << ") but is unprintable there";
|
||||
violations.push_back(ss.str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. unprintable_volumes check
|
||||
for (auto& [fil, volume_types] : ctx.model_info.unprintable_volumes) {
|
||||
if (fil < 0 || fil >= (int)filament_map.size())
|
||||
continue;
|
||||
int assigned_nozzle = filament_map[fil];
|
||||
if (assigned_nozzle < 0 || assigned_nozzle >= (int)ctx.nozzle_info.nozzle_list.size())
|
||||
continue;
|
||||
if (volume_types.count(ctx.nozzle_info.nozzle_list[assigned_nozzle].volume_type)) {
|
||||
std::ostringstream ss;
|
||||
ss << "filament " << fil << " assigned to nozzle " << assigned_nozzle
|
||||
<< " with volume_type " << (int)ctx.nozzle_info.nozzle_list[assigned_nozzle].volume_type
|
||||
<< " but that type is unprintable for this filament";
|
||||
violations.push_back(ss.str());
|
||||
}
|
||||
}
|
||||
|
||||
// 3. max_group_size per extruder. This cap is an invariant of the flush-partition
|
||||
// modes only: those solvers partition the filaments across extruders subject to
|
||||
// each extruder's capacity. MatchMode instead maps every filament to the extruder
|
||||
// holding the nearest-color loaded AMS filament and does not partition by capacity
|
||||
// (its solver capacity is the filament count, not max_group_size), so a legitimate
|
||||
// match may place more than max_group_size filaments on one extruder. Enforce the
|
||||
// cap only for the partition modes, and only when the instance is feasible.
|
||||
int total_capacity = 0;
|
||||
for (auto sz : ctx.machine_info.max_group_size)
|
||||
total_capacity += sz;
|
||||
|
||||
if (ctx.group_info.mode != FGMode::MatchMode &&
|
||||
total_capacity >= (int)used_filaments.size()) {
|
||||
std::map<int, int> extruder_count;
|
||||
for (auto fil : used_filaments) {
|
||||
if (fil >= filament_map.size()) continue;
|
||||
int nozzle_id = filament_map[fil];
|
||||
if (nozzle_id < 0 || nozzle_id >= (int)ctx.nozzle_info.nozzle_list.size())
|
||||
continue;
|
||||
extruder_count[ctx.nozzle_info.nozzle_list[nozzle_id].extruder_id]++;
|
||||
}
|
||||
for (auto& [ext, count] : extruder_count) {
|
||||
if (ext >= 0 && ext < (int)ctx.machine_info.max_group_size.size()) {
|
||||
if (count > ctx.machine_info.max_group_size[ext]) {
|
||||
std::ostringstream ss;
|
||||
ss << "extruder " << ext << " has " << count << " filaments but max is "
|
||||
<< ctx.machine_info.max_group_size[ext];
|
||||
violations.push_back(ss.str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return violations.empty();
|
||||
}
|
||||
|
||||
inline int compute_flush_cost(const FilamentGroupContext& ctx,
|
||||
const std::vector<int>& filament_map) {
|
||||
auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments);
|
||||
if (used_filaments.empty())
|
||||
return 0;
|
||||
|
||||
auto nozzle_group_result = MultiNozzleUtils::LayeredNozzleGroupResult::create(
|
||||
filament_map, ctx.nozzle_info.nozzle_list, used_filaments);
|
||||
|
||||
if (!nozzle_group_result)
|
||||
return -1;
|
||||
|
||||
std::vector<std::vector<unsigned int>> filament_sequences;
|
||||
auto get_custom_seq_null = [](int, std::vector<int>&) -> bool { return false; };
|
||||
|
||||
int cost = reorder_filaments_for_multi_nozzle_extruder(
|
||||
used_filaments,
|
||||
*nozzle_group_result,
|
||||
ctx.model_info.layer_filaments,
|
||||
ctx.model_info.flush_matrix,
|
||||
get_custom_seq_null,
|
||||
&filament_sequences,
|
||||
MultiNozzleUtils::NozzleStatusRecorder{});
|
||||
|
||||
return cost;
|
||||
}
|
||||
|
||||
struct FullEvalResult {
|
||||
int flush_cost = 0;
|
||||
double change_time = 0.0;
|
||||
double full_score = 0.0;
|
||||
bool constraints_ok = true;
|
||||
std::vector<std::string> violations;
|
||||
};
|
||||
|
||||
inline double evaluate_score(double flush, double time) {
|
||||
double approx_density = 1.26;
|
||||
double approx_flush_speed = 180;
|
||||
double correction_factor = 2;
|
||||
double flush_score = flush * approx_density * approx_flush_speed * correction_factor / 1000;
|
||||
return flush_score + time;
|
||||
}
|
||||
|
||||
inline double calc_change_time_for_group_eval(
|
||||
const std::vector<int>& filament_change_seq,
|
||||
const std::vector<int>& nozzle_change_seq,
|
||||
const std::vector<int>& logical_filaments,
|
||||
const std::vector<MultiNozzleUtils::NozzleInfo>& nozzle_list,
|
||||
const MultiNozzleUtils::FilamentChangeTimeParams& time_params,
|
||||
const std::vector<bool>& ams_preload_enabled,
|
||||
const std::vector<int>& group_of_filament)
|
||||
{
|
||||
auto r = MultiNozzleUtils::simulate_filament_change_time(
|
||||
logical_filaments, nozzle_list, filament_change_seq,
|
||||
nozzle_change_seq, group_of_filament, time_params,
|
||||
ams_preload_enabled);
|
||||
return r.actual_time;
|
||||
}
|
||||
|
||||
inline FullEvalResult full_evaluate_map(const FilamentGroupContext& ctx,
|
||||
const std::vector<int>& filament_map) {
|
||||
FullEvalResult result;
|
||||
auto used_filaments = collect_sorted_used_filaments(ctx.model_info.layer_filaments);
|
||||
if (used_filaments.empty()) return result;
|
||||
|
||||
auto nozzle_group_result = MultiNozzleUtils::LayeredNozzleGroupResult::create(
|
||||
filament_map, ctx.nozzle_info.nozzle_list, used_filaments);
|
||||
if (!nozzle_group_result) return result;
|
||||
|
||||
MultiNozzleUtils::NozzleStatusRecorder initial_status;
|
||||
for (auto& [nozzle_id, filament_id] : ctx.nozzle_info.nozzle_status) {
|
||||
if (filament_id >= 0) {
|
||||
int extruder_id = 0;
|
||||
for (const auto& nozzle : ctx.nozzle_info.nozzle_list) {
|
||||
if (nozzle.group_id == nozzle_id) { extruder_id = nozzle.extruder_id; break; }
|
||||
}
|
||||
initial_status.set_nozzle_status(nozzle_id, filament_id, extruder_id);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::vector<unsigned int>> filament_sequences;
|
||||
auto get_custom_seq_null = [](int, std::vector<int>&) -> bool { return false; };
|
||||
|
||||
result.flush_cost = reorder_filaments_for_multi_nozzle_extruder(
|
||||
used_filaments, *nozzle_group_result, ctx.model_info.layer_filaments,
|
||||
ctx.model_info.flush_matrix, get_custom_seq_null, &filament_sequences, initial_status);
|
||||
|
||||
if (!filament_sequences.empty()) {
|
||||
std::vector<int> filament_change_seq;
|
||||
std::vector<int> nozzle_change_seq;
|
||||
int prev_fil = -1, prev_nozzle = -1;
|
||||
for (const auto& layer_seq : filament_sequences) {
|
||||
for (unsigned int fil : layer_seq) {
|
||||
auto nozzle_info = nozzle_group_result->get_first_nozzle_for_filament(fil);
|
||||
if (!nozzle_info) continue;
|
||||
int nid = nozzle_info->group_id;
|
||||
if ((int)fil == prev_fil && nid == prev_nozzle) continue;
|
||||
filament_change_seq.push_back((int)fil);
|
||||
nozzle_change_seq.push_back(nid);
|
||||
prev_fil = (int)fil;
|
||||
prev_nozzle = nid;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<int> logical_filaments(used_filaments.begin(), used_filaments.end());
|
||||
std::vector<int> group_of_filament(used_filaments.size(), 0);
|
||||
for (size_t fi = 0; fi < used_filaments.size(); ++fi) {
|
||||
int nid = filament_map[used_filaments[fi]];
|
||||
if (nid >= 0 && nid < (int)ctx.nozzle_info.nozzle_list.size())
|
||||
group_of_filament[fi] = ctx.nozzle_info.nozzle_list[nid].extruder_id;
|
||||
}
|
||||
result.change_time = calc_change_time_for_group_eval(
|
||||
filament_change_seq, nozzle_change_seq, logical_filaments,
|
||||
ctx.nozzle_info.nozzle_list, ctx.speed_info.change_time_params,
|
||||
ctx.speed_info.ams_preload_enabled, group_of_filament);
|
||||
}
|
||||
|
||||
result.full_score = evaluate_score(result.flush_cost, result.change_time);
|
||||
result.constraints_ok = check_constraints(ctx, filament_map, result.violations);
|
||||
return result;
|
||||
}
|
||||
|
||||
inline TestResult run_and_evaluate(const FilamentGroupContext& ctx,
|
||||
const ClusteringBudget& budget = {}) {
|
||||
TestResult result;
|
||||
|
||||
auto start = std::chrono::high_resolution_clock::now();
|
||||
int algo_cost = 0;
|
||||
|
||||
FilamentGroup fg(ctx);
|
||||
fg.set_clustering_budget(budget);
|
||||
result.filament_map = fg.calc_filament_group(&algo_cost);
|
||||
|
||||
auto end = std::chrono::high_resolution_clock::now();
|
||||
result.elapsed_ms = std::chrono::duration<double, std::milli>(end - start).count();
|
||||
|
||||
result.flush_cost = compute_flush_cost(ctx, result.filament_map);
|
||||
|
||||
result.constraints_ok = check_constraints(ctx, result.filament_map, result.violations);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace FGTest
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif // FG_TEST_EVALUATOR_HPP
|
||||
447
tests/filament_group/fg_test_serialization.hpp
Normal file
447
tests/filament_group/fg_test_serialization.hpp
Normal file
@@ -0,0 +1,447 @@
|
||||
#ifndef FG_TEST_SERIALIZATION_HPP
|
||||
#define FG_TEST_SERIALIZATION_HPP
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <libslic3r/FilamentGroup.hpp>
|
||||
#include <libslic3r/FilamentGroupUtils.hpp>
|
||||
#include <libslic3r/MultiNozzleUtils.hpp>
|
||||
#include <libslic3r/PrintConfig.hpp>
|
||||
|
||||
#include <fstream>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <map>
|
||||
#include <unordered_map>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
// Put serializers in correct ADL namespaces for each type
|
||||
|
||||
namespace Slic3r {
|
||||
namespace FilamentGroupUtils {
|
||||
|
||||
inline void to_json(json& j, const Color& c) {
|
||||
char buf[10];
|
||||
snprintf(buf, sizeof(buf), "#%02X%02X%02X%02X", c.r, c.g, c.b, c.a);
|
||||
j = std::string(buf);
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, Color& c) {
|
||||
std::string s = j.get<std::string>();
|
||||
if (s.size() >= 7 && s[0] == '#') {
|
||||
c.r = (unsigned char)std::stoi(s.substr(1, 2), nullptr, 16);
|
||||
c.g = (unsigned char)std::stoi(s.substr(3, 2), nullptr, 16);
|
||||
c.b = (unsigned char)std::stoi(s.substr(5, 2), nullptr, 16);
|
||||
c.a = (s.size() >= 9) ? (unsigned char)std::stoi(s.substr(7, 2), nullptr, 16) : 255;
|
||||
}
|
||||
}
|
||||
|
||||
inline void to_json(json& j, const FilamentInfo& fi) {
|
||||
j = json{
|
||||
{"color", fi.color},
|
||||
{"type", fi.type},
|
||||
{"is_support", fi.is_support},
|
||||
{"usage_type", (int)fi.usage_type}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentInfo& fi) {
|
||||
fi.color = j.at("color").get<Color>();
|
||||
j.at("type").get_to(fi.type);
|
||||
j.at("is_support").get_to(fi.is_support);
|
||||
fi.usage_type = (FilamentUsageType)j.at("usage_type").get<int>();
|
||||
}
|
||||
|
||||
inline void to_json(json& j, const MachineFilamentInfo& mfi) {
|
||||
j = json{
|
||||
{"color", mfi.color},
|
||||
{"type", mfi.type},
|
||||
{"is_support", mfi.is_support},
|
||||
{"usage_type", (int)mfi.usage_type},
|
||||
{"extruder_id", mfi.extruder_id},
|
||||
{"is_extended", mfi.is_extended}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, MachineFilamentInfo& mfi) {
|
||||
mfi.color = j.at("color").get<Color>();
|
||||
j.at("type").get_to(mfi.type);
|
||||
j.at("is_support").get_to(mfi.is_support);
|
||||
mfi.usage_type = (FilamentUsageType)j.at("usage_type").get<int>();
|
||||
j.at("extruder_id").get_to(mfi.extruder_id);
|
||||
j.at("is_extended").get_to(mfi.is_extended);
|
||||
}
|
||||
|
||||
} // namespace FilamentGroupUtils
|
||||
|
||||
namespace MultiNozzleUtils {
|
||||
|
||||
inline void to_json(json& j, const NozzleInfo& ni) {
|
||||
j = json{
|
||||
{"diameter", ni.diameter},
|
||||
{"volume_type", (int)ni.volume_type},
|
||||
{"extruder_id", ni.extruder_id},
|
||||
{"group_id", ni.group_id}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, NozzleInfo& ni) {
|
||||
j.at("diameter").get_to(ni.diameter);
|
||||
ni.volume_type = (NozzleVolumeType)j.at("volume_type").get<int>();
|
||||
j.at("extruder_id").get_to(ni.extruder_id);
|
||||
j.at("group_id").get_to(ni.group_id);
|
||||
}
|
||||
|
||||
inline void to_json(json& j, const FilamentChangeTimeParams& p) {
|
||||
j = json{
|
||||
{"selector_load_time", p.selector_load_time},
|
||||
{"selector_unload_time", p.selector_unload_time},
|
||||
{"standard_load_time", p.standard_load_time},
|
||||
{"standard_unload_time", p.standard_unload_time}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentChangeTimeParams& p) {
|
||||
j.at("selector_load_time").get_to(p.selector_load_time);
|
||||
j.at("selector_unload_time").get_to(p.selector_unload_time);
|
||||
j.at("standard_load_time").get_to(p.standard_load_time);
|
||||
j.at("standard_unload_time").get_to(p.standard_unload_time);
|
||||
}
|
||||
|
||||
} // namespace MultiNozzleUtils
|
||||
|
||||
// ============ Helper: set<int> as JSON array ============
|
||||
namespace FGTestDetail {
|
||||
inline json set_to_json(const std::set<int>& s) {
|
||||
return json(std::vector<int>(s.begin(), s.end()));
|
||||
}
|
||||
|
||||
inline std::set<int> json_to_set(const json& j) {
|
||||
auto v = j.get<std::vector<int>>();
|
||||
return std::set<int>(v.begin(), v.end());
|
||||
}
|
||||
|
||||
inline json nvt_set_to_json(const std::set<NozzleVolumeType>& s) {
|
||||
std::vector<int> v;
|
||||
for (auto t : s) v.push_back((int)t);
|
||||
return json(v);
|
||||
}
|
||||
|
||||
inline std::set<NozzleVolumeType> json_to_nvt_set(const json& j) {
|
||||
std::set<NozzleVolumeType> s;
|
||||
for (auto& item : j) s.insert((NozzleVolumeType)item.get<int>());
|
||||
return s;
|
||||
}
|
||||
} // namespace FGTestDetail
|
||||
|
||||
// ============ FilamentGroupContext::ModelInfo ============
|
||||
inline void to_json(json& j, const FilamentGroupContext::ModelInfo& mi) {
|
||||
using namespace FGTestDetail;
|
||||
j["flush_matrix"] = mi.flush_matrix;
|
||||
j["layer_filaments"] = mi.layer_filaments;
|
||||
|
||||
j["filament_info"] = json::array();
|
||||
for (auto& fi : mi.filament_info)
|
||||
j["filament_info"].push_back(fi);
|
||||
|
||||
j["filament_ids"] = mi.filament_ids;
|
||||
|
||||
j["unprintable_filaments"] = json::array();
|
||||
for (auto& s : mi.unprintable_filaments)
|
||||
j["unprintable_filaments"].push_back(set_to_json(s));
|
||||
|
||||
json uv = json::object();
|
||||
for (auto& [fil, types] : mi.unprintable_volumes)
|
||||
uv[std::to_string(fil)] = nvt_set_to_json(types);
|
||||
j["unprintable_volumes"] = uv;
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext::ModelInfo& mi) {
|
||||
using namespace FGTestDetail;
|
||||
j.at("flush_matrix").get_to(mi.flush_matrix);
|
||||
j.at("layer_filaments").get_to(mi.layer_filaments);
|
||||
|
||||
mi.filament_info.clear();
|
||||
for (auto& item : j.at("filament_info"))
|
||||
mi.filament_info.push_back(item.get<FilamentGroupUtils::FilamentInfo>());
|
||||
|
||||
j.at("filament_ids").get_to(mi.filament_ids);
|
||||
|
||||
mi.unprintable_filaments.clear();
|
||||
for (auto& item : j.at("unprintable_filaments"))
|
||||
mi.unprintable_filaments.push_back(json_to_set(item));
|
||||
|
||||
mi.unprintable_volumes.clear();
|
||||
if (j.contains("unprintable_volumes")) {
|
||||
for (auto& [k, v] : j.at("unprintable_volumes").items())
|
||||
mi.unprintable_volumes[std::stoi(k)] = json_to_nvt_set(v);
|
||||
}
|
||||
}
|
||||
|
||||
// ============ FilamentGroupContext::GroupInfo ============
|
||||
inline void to_json(json& j, const FilamentGroupContext::GroupInfo& gi) {
|
||||
j = json{
|
||||
{"total_filament_num", gi.total_filament_num},
|
||||
{"max_gap_threshold", gi.max_gap_threshold},
|
||||
{"mode", (int)gi.mode},
|
||||
{"strategy", (int)gi.strategy},
|
||||
{"ignore_ext_filament", gi.ignore_ext_filament},
|
||||
{"has_filament_switcher", gi.has_filament_switcher},
|
||||
{"filament_volume_map", gi.filament_volume_map}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext::GroupInfo& gi) {
|
||||
j.at("total_filament_num").get_to(gi.total_filament_num);
|
||||
j.at("max_gap_threshold").get_to(gi.max_gap_threshold);
|
||||
gi.mode = (FGMode)j.at("mode").get<int>();
|
||||
gi.strategy = (FGStrategy)j.at("strategy").get<int>();
|
||||
j.at("ignore_ext_filament").get_to(gi.ignore_ext_filament);
|
||||
j.at("has_filament_switcher").get_to(gi.has_filament_switcher);
|
||||
j.at("filament_volume_map").get_to(gi.filament_volume_map);
|
||||
}
|
||||
|
||||
// ============ FilamentGroupContext::MachineInfo ============
|
||||
inline void to_json(json& j, const FilamentGroupContext::MachineInfo& mi) {
|
||||
j["max_group_size"] = mi.max_group_size;
|
||||
|
||||
j["machine_filament_info"] = json::array();
|
||||
for (auto& vec : mi.machine_filament_info) {
|
||||
json arr = json::array();
|
||||
for (auto& mfi : vec) arr.push_back(mfi);
|
||||
j["machine_filament_info"].push_back(arr);
|
||||
}
|
||||
|
||||
j["prefer_non_model_filament"] = mi.prefer_non_model_filament;
|
||||
j["master_extruder_id"] = mi.master_extruder_id;
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext::MachineInfo& mi) {
|
||||
j.at("max_group_size").get_to(mi.max_group_size);
|
||||
|
||||
mi.machine_filament_info.clear();
|
||||
for (auto& arr : j.at("machine_filament_info")) {
|
||||
std::vector<FilamentGroupUtils::MachineFilamentInfo> vec;
|
||||
for (auto& item : arr)
|
||||
vec.push_back(item.get<FilamentGroupUtils::MachineFilamentInfo>());
|
||||
mi.machine_filament_info.push_back(std::move(vec));
|
||||
}
|
||||
|
||||
j.at("prefer_non_model_filament").get_to(mi.prefer_non_model_filament);
|
||||
j.at("master_extruder_id").get_to(mi.master_extruder_id);
|
||||
}
|
||||
|
||||
// ============ FilamentGroupContext::SpeedInfo ============
|
||||
inline void to_json(json& j, const FilamentGroupContext::SpeedInfo& si) {
|
||||
json fpt = json::object();
|
||||
for (auto& [fil, inner] : si.filament_print_time) {
|
||||
json inner_j = json::object();
|
||||
for (auto& [layer, time] : inner)
|
||||
inner_j[std::to_string(layer)] = time;
|
||||
fpt[std::to_string(fil)] = inner_j;
|
||||
}
|
||||
j["filament_print_time"] = fpt;
|
||||
j["extruder_change_time"] = si.extruder_change_time;
|
||||
j["filament_change_time"] = si.filament_change_time;
|
||||
j["group_with_time"] = si.group_with_time;
|
||||
j["change_time_params"] = si.change_time_params;
|
||||
j["ams_preload_enabled"] = si.ams_preload_enabled;
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext::SpeedInfo& si) {
|
||||
si.filament_print_time.clear();
|
||||
if (j.contains("filament_print_time")) {
|
||||
for (auto& [k, v] : j.at("filament_print_time").items()) {
|
||||
int fil = std::stoi(k);
|
||||
for (auto& [k2, v2] : v.items())
|
||||
si.filament_print_time[fil][std::stoi(k2)] = v2.get<double>();
|
||||
}
|
||||
}
|
||||
j.at("extruder_change_time").get_to(si.extruder_change_time);
|
||||
j.at("filament_change_time").get_to(si.filament_change_time);
|
||||
j.at("group_with_time").get_to(si.group_with_time);
|
||||
si.change_time_params = j.at("change_time_params").get<MultiNozzleUtils::FilamentChangeTimeParams>();
|
||||
j.at("ams_preload_enabled").get_to(si.ams_preload_enabled);
|
||||
}
|
||||
|
||||
// ============ FilamentGroupContext::NozzleInfo ============
|
||||
inline void to_json(json& j, const FilamentGroupContext::NozzleInfo& ni) {
|
||||
json enl = json::object();
|
||||
for (auto& [ext, nozzles] : ni.extruder_nozzle_list)
|
||||
enl[std::to_string(ext)] = nozzles;
|
||||
j["extruder_nozzle_list"] = enl;
|
||||
|
||||
j["nozzle_list"] = json::array();
|
||||
for (auto& n : ni.nozzle_list)
|
||||
j["nozzle_list"].push_back(n);
|
||||
|
||||
json ns = json::object();
|
||||
for (auto& [noz, fil] : ni.nozzle_status)
|
||||
ns[std::to_string(noz)] = fil;
|
||||
j["nozzle_status"] = ns;
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext::NozzleInfo& ni) {
|
||||
ni.extruder_nozzle_list.clear();
|
||||
for (auto& [k, v] : j.at("extruder_nozzle_list").items())
|
||||
ni.extruder_nozzle_list[std::stoi(k)] = v.get<std::vector<int>>();
|
||||
|
||||
ni.nozzle_list.clear();
|
||||
for (auto& item : j.at("nozzle_list"))
|
||||
ni.nozzle_list.push_back(item.get<MultiNozzleUtils::NozzleInfo>());
|
||||
|
||||
ni.nozzle_status.clear();
|
||||
if (j.contains("nozzle_status")) {
|
||||
for (auto& [k, v] : j.at("nozzle_status").items())
|
||||
ni.nozzle_status[std::stoi(k)] = v.get<int>();
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Full FilamentGroupContext ============
|
||||
inline void to_json(json& j, const FilamentGroupContext& ctx) {
|
||||
json mi, gi, mai, si, ni;
|
||||
to_json(mi, ctx.model_info);
|
||||
to_json(gi, ctx.group_info);
|
||||
to_json(mai, ctx.machine_info);
|
||||
to_json(si, ctx.speed_info);
|
||||
to_json(ni, ctx.nozzle_info);
|
||||
j["model_info"] = mi;
|
||||
j["group_info"] = gi;
|
||||
j["machine_info"] = mai;
|
||||
j["speed_info"] = si;
|
||||
j["nozzle_info"] = ni;
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, FilamentGroupContext& ctx) {
|
||||
from_json(j.at("model_info"), ctx.model_info);
|
||||
from_json(j.at("group_info"), ctx.group_info);
|
||||
from_json(j.at("machine_info"), ctx.machine_info);
|
||||
from_json(j.at("speed_info"), ctx.speed_info);
|
||||
from_json(j.at("nozzle_info"), ctx.nozzle_info);
|
||||
}
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
// ============ Test-specific types in FGTest namespace ============
|
||||
namespace Slic3r {
|
||||
namespace FGTest {
|
||||
|
||||
struct TestMetadata {
|
||||
std::string id;
|
||||
std::string config_type;
|
||||
int seed = 0;
|
||||
};
|
||||
|
||||
inline void to_json(json& j, const TestMetadata& m) {
|
||||
j = json{{"id", m.id}, {"config_type", m.config_type}, {"seed", m.seed}};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, TestMetadata& m) {
|
||||
j.at("id").get_to(m.id);
|
||||
j.at("config_type").get_to(m.config_type);
|
||||
j.at("seed").get_to(m.seed);
|
||||
}
|
||||
|
||||
struct TestResult {
|
||||
std::vector<int> filament_map;
|
||||
int flush_cost = 0;
|
||||
double elapsed_ms = 0;
|
||||
bool constraints_ok = true;
|
||||
std::vector<std::string> violations;
|
||||
};
|
||||
|
||||
inline void to_json(json& j, const TestResult& r) {
|
||||
j = json{
|
||||
{"filament_map", r.filament_map},
|
||||
{"flush_cost", r.flush_cost},
|
||||
{"elapsed_ms", r.elapsed_ms},
|
||||
{"constraints_ok", r.constraints_ok},
|
||||
{"violations", r.violations}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, TestResult& r) {
|
||||
j.at("filament_map").get_to(r.filament_map);
|
||||
j.at("flush_cost").get_to(r.flush_cost);
|
||||
j.at("elapsed_ms").get_to(r.elapsed_ms);
|
||||
j.at("constraints_ok").get_to(r.constraints_ok);
|
||||
if (j.contains("violations"))
|
||||
j.at("violations").get_to(r.violations);
|
||||
}
|
||||
|
||||
// ============ Base Result (golden baseline stored in input file) ============
|
||||
struct BaseResult {
|
||||
double full_score = 0;
|
||||
int flush_cost = 0;
|
||||
bool constraints_ok = true;
|
||||
};
|
||||
|
||||
inline void to_json(json& j, const BaseResult& g) {
|
||||
j = json{
|
||||
{"full_score", g.full_score},
|
||||
{"flush_cost", g.flush_cost},
|
||||
{"constraints_ok", g.constraints_ok}
|
||||
};
|
||||
}
|
||||
|
||||
inline void from_json(const json& j, BaseResult& g) {
|
||||
j.at("full_score").get_to(g.full_score);
|
||||
j.at("flush_cost").get_to(g.flush_cost);
|
||||
j.at("constraints_ok").get_to(g.constraints_ok);
|
||||
}
|
||||
|
||||
// ============ File I/O ============
|
||||
struct TestCase {
|
||||
TestMetadata metadata;
|
||||
FilamentGroupContext context;
|
||||
std::optional<BaseResult> base_result;
|
||||
};
|
||||
|
||||
inline TestCase load_test_case(const std::string& path) {
|
||||
std::ifstream f(path);
|
||||
json j = json::parse(f);
|
||||
TestCase tc;
|
||||
tc.metadata = j.at("metadata").get<TestMetadata>();
|
||||
Slic3r::from_json(j.at("context"), tc.context);
|
||||
if (j.contains("base_result"))
|
||||
tc.base_result = j.at("base_result").get<BaseResult>();
|
||||
return tc;
|
||||
}
|
||||
|
||||
inline void save_test_case(const std::string& path, const TestCase& tc) {
|
||||
json j;
|
||||
j["metadata"] = tc.metadata;
|
||||
json ctx_j;
|
||||
Slic3r::to_json(ctx_j, tc.context);
|
||||
j["context"] = ctx_j;
|
||||
if (tc.base_result)
|
||||
j["base_result"] = *tc.base_result;
|
||||
std::ofstream f(path);
|
||||
f << j.dump(-1);
|
||||
}
|
||||
|
||||
inline void save_result(const std::string& case_path, const TestResult& result) {
|
||||
std::string result_path = case_path;
|
||||
auto pos = result_path.rfind(".json");
|
||||
if (pos != std::string::npos)
|
||||
result_path = result_path.substr(0, pos) + ".result.json";
|
||||
else
|
||||
result_path += ".result.json";
|
||||
|
||||
json j = result;
|
||||
std::ofstream f(result_path);
|
||||
f << j.dump(2);
|
||||
}
|
||||
|
||||
inline TestResult load_result(const std::string& result_path) {
|
||||
std::ifstream f(result_path);
|
||||
json j = json::parse(f);
|
||||
return j.get<TestResult>();
|
||||
}
|
||||
|
||||
} // namespace FGTest
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif // FG_TEST_SERIALIZATION_HPP
|
||||
406
tests/filament_group/fg_test_utils.hpp
Normal file
406
tests/filament_group/fg_test_utils.hpp
Normal file
@@ -0,0 +1,406 @@
|
||||
#ifndef FG_TEST_UTILS_HPP
|
||||
#define FG_TEST_UTILS_HPP
|
||||
|
||||
#include "fg_test_serialization.hpp"
|
||||
#include <random>
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
|
||||
namespace Slic3r {
|
||||
namespace FGTest {
|
||||
|
||||
class TestRng {
|
||||
public:
|
||||
explicit TestRng(int seed) : m_gen(seed) {}
|
||||
|
||||
int rand_int(int lo, int hi) {
|
||||
std::uniform_int_distribution<int> dist(lo, hi);
|
||||
return dist(m_gen);
|
||||
}
|
||||
|
||||
float rand_float(float lo, float hi) {
|
||||
std::uniform_real_distribution<float> dist(lo, hi);
|
||||
return dist(m_gen);
|
||||
}
|
||||
|
||||
double rand_double(double lo, double hi) {
|
||||
std::uniform_real_distribution<double> dist(lo, hi);
|
||||
return dist(m_gen);
|
||||
}
|
||||
|
||||
bool rand_bool(double prob = 0.5) {
|
||||
return rand_double(0, 1) < prob;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void shuffle(std::vector<T>& v) {
|
||||
std::shuffle(v.begin(), v.end(), m_gen);
|
||||
}
|
||||
|
||||
private:
|
||||
std::mt19937 m_gen;
|
||||
};
|
||||
|
||||
// Generate a flush matrix for one extruder: [filament_count x filament_count]
|
||||
inline std::vector<std::vector<float>> generate_flush_matrix(int filament_count, TestRng& rng) {
|
||||
std::vector<std::vector<float>> matrix(filament_count, std::vector<float>(filament_count, 0.0f));
|
||||
for (int i = 0; i < filament_count; ++i) {
|
||||
for (int j = 0; j < filament_count; ++j) {
|
||||
if (i == j)
|
||||
matrix[i][j] = 0.0f;
|
||||
else
|
||||
matrix[i][j] = rng.rand_float(10.0f, 600.0f);
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
|
||||
// Generate layer_filaments with interval characteristics
|
||||
inline std::vector<std::vector<unsigned int>> generate_layer_filaments_interval(
|
||||
int num_layers, int total_filaments, const std::vector<unsigned int>& used_filaments, TestRng& rng)
|
||||
{
|
||||
std::vector<std::vector<unsigned int>> layers;
|
||||
layers.reserve(num_layers);
|
||||
|
||||
int n_used = (int)used_filaments.size();
|
||||
int fils_per_layer_min = std::min(2, n_used);
|
||||
int fils_per_layer_max = std::min(n_used, std::max(2, n_used / 2 + 1));
|
||||
|
||||
// First layer: random subset
|
||||
int first_count = rng.rand_int(fils_per_layer_min, fils_per_layer_max);
|
||||
std::vector<unsigned int> pool = used_filaments;
|
||||
rng.shuffle(pool);
|
||||
std::vector<unsigned int> current(pool.begin(), pool.begin() + first_count);
|
||||
std::sort(current.begin(), current.end());
|
||||
layers.push_back(current);
|
||||
|
||||
for (int layer = 1; layer < num_layers; ++layer) {
|
||||
// 10% chance: completely random new set (object boundary)
|
||||
if (rng.rand_bool(0.10)) {
|
||||
int count = rng.rand_int(fils_per_layer_min, fils_per_layer_max);
|
||||
pool = used_filaments;
|
||||
rng.shuffle(pool);
|
||||
current.assign(pool.begin(), pool.begin() + count);
|
||||
} else {
|
||||
// Markov: keep each filament with 70% prob, maybe add new ones
|
||||
std::vector<unsigned int> next;
|
||||
for (auto f : current) {
|
||||
if (rng.rand_bool(0.70))
|
||||
next.push_back(f);
|
||||
}
|
||||
// Maybe add a filament not in current
|
||||
if (rng.rand_bool(0.30) || next.empty()) {
|
||||
std::vector<unsigned int> candidates;
|
||||
std::set<unsigned int> cur_set(next.begin(), next.end());
|
||||
for (auto f : used_filaments) {
|
||||
if (!cur_set.count(f))
|
||||
candidates.push_back(f);
|
||||
}
|
||||
if (!candidates.empty()) {
|
||||
next.push_back(candidates[rng.rand_int(0, (int)candidates.size() - 1)]);
|
||||
}
|
||||
}
|
||||
if (next.empty())
|
||||
next.push_back(used_filaments[rng.rand_int(0, n_used - 1)]);
|
||||
current = next;
|
||||
}
|
||||
std::sort(current.begin(), current.end());
|
||||
current.erase(std::unique(current.begin(), current.end()), current.end());
|
||||
layers.push_back(current);
|
||||
}
|
||||
|
||||
return layers;
|
||||
}
|
||||
|
||||
// Generate layer_filaments where every layer is different (stress/edge)
|
||||
inline std::vector<std::vector<unsigned int>> generate_layer_filaments_chaotic(
|
||||
int num_layers, int total_filaments, const std::vector<unsigned int>& used_filaments, TestRng& rng)
|
||||
{
|
||||
std::vector<std::vector<unsigned int>> layers;
|
||||
int n_used = (int)used_filaments.size();
|
||||
int fils_per_layer_min = std::min(2, n_used);
|
||||
int fils_per_layer_max = n_used;
|
||||
|
||||
for (int layer = 0; layer < num_layers; ++layer) {
|
||||
int count = rng.rand_int(fils_per_layer_min, fils_per_layer_max);
|
||||
std::vector<unsigned int> pool = used_filaments;
|
||||
rng.shuffle(pool);
|
||||
std::vector<unsigned int> current(pool.begin(), pool.begin() + count);
|
||||
std::sort(current.begin(), current.end());
|
||||
layers.push_back(current);
|
||||
}
|
||||
return layers;
|
||||
}
|
||||
|
||||
// Generate layer_filaments where all layers are the same (edge)
|
||||
inline std::vector<std::vector<unsigned int>> generate_layer_filaments_uniform(
|
||||
int num_layers, const std::vector<unsigned int>& used_filaments)
|
||||
{
|
||||
return std::vector<std::vector<unsigned int>>(num_layers, used_filaments);
|
||||
}
|
||||
|
||||
// Generate filament info
|
||||
inline std::vector<FilamentGroupUtils::FilamentInfo> generate_filament_info(int count, TestRng& rng) {
|
||||
static const char* types[] = {"PLA", "ABS", "PETG", "TPU", "PA", "PLA-S"};
|
||||
std::vector<FilamentGroupUtils::FilamentInfo> infos;
|
||||
for (int i = 0; i < count; ++i) {
|
||||
FilamentGroupUtils::FilamentInfo fi;
|
||||
fi.color = FilamentGroupUtils::Color(
|
||||
(unsigned char)rng.rand_int(0, 255),
|
||||
(unsigned char)rng.rand_int(0, 255),
|
||||
(unsigned char)rng.rand_int(0, 255));
|
||||
fi.type = types[rng.rand_int(0, 5)];
|
||||
fi.is_support = (fi.type == "PLA-S");
|
||||
fi.usage_type = fi.is_support ? FilamentUsageType::SupportOnly : FilamentUsageType::ModelOnly;
|
||||
infos.push_back(fi);
|
||||
}
|
||||
return infos;
|
||||
}
|
||||
|
||||
// Generate machine filament info (per extruder)
|
||||
inline std::vector<std::vector<FilamentGroupUtils::MachineFilamentInfo>> generate_machine_filament_info(
|
||||
int num_extruders, int filaments_per_extruder, TestRng& rng)
|
||||
{
|
||||
std::vector<std::vector<FilamentGroupUtils::MachineFilamentInfo>> result;
|
||||
for (int ext = 0; ext < num_extruders; ++ext) {
|
||||
std::vector<FilamentGroupUtils::MachineFilamentInfo> vec;
|
||||
for (int i = 0; i < filaments_per_extruder; ++i) {
|
||||
FilamentGroupUtils::MachineFilamentInfo mfi;
|
||||
mfi.color = FilamentGroupUtils::Color(
|
||||
(unsigned char)rng.rand_int(0, 255),
|
||||
(unsigned char)rng.rand_int(0, 255),
|
||||
(unsigned char)rng.rand_int(0, 255));
|
||||
mfi.type = "PLA";
|
||||
mfi.is_support = false;
|
||||
mfi.usage_type = FilamentUsageType::ModelOnly;
|
||||
mfi.extruder_id = ext;
|
||||
mfi.is_extended = (i >= 4);
|
||||
vec.push_back(mfi);
|
||||
}
|
||||
result.push_back(vec);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ============ Machine Config Builders ============
|
||||
|
||||
// Config A: 2 extruders, 1 nozzle each
|
||||
inline void build_config_a(FilamentGroupContext& ctx, int num_filaments, TestRng& rng) {
|
||||
auto& ni = ctx.nozzle_info;
|
||||
ni.nozzle_list.clear();
|
||||
ni.nozzle_list.push_back({"0.4", NozzleVolumeType::nvtStandard, 0, 0});
|
||||
ni.nozzle_list.push_back({"0.4", NozzleVolumeType::nvtStandard, 1, 1});
|
||||
ni.extruder_nozzle_list = {{0, {0}}, {1, {1}}};
|
||||
|
||||
ctx.machine_info.max_group_size = {num_filaments / 2 + 1, num_filaments / 2 + 1};
|
||||
ctx.machine_info.prefer_non_model_filament = {false, true};
|
||||
ctx.machine_info.master_extruder_id = 0;
|
||||
ctx.machine_info.machine_filament_info = generate_machine_filament_info(2, 4, rng);
|
||||
|
||||
ctx.group_info.filament_volume_map.assign(num_filaments, (int)NozzleVolumeType::nvtHybrid);
|
||||
|
||||
ctx.model_info.unprintable_filaments.resize(2);
|
||||
ctx.model_info.flush_matrix.resize(2);
|
||||
for (int ext = 0; ext < 2; ++ext)
|
||||
ctx.model_info.flush_matrix[ext] = generate_flush_matrix(num_filaments, rng);
|
||||
}
|
||||
|
||||
// Config B: 2 extruders, ext0 has 1 nozzle, ext1 has K nozzles (K in [2,6])
|
||||
inline void build_config_b(FilamentGroupContext& ctx, int num_filaments, int k_nozzles, TestRng& rng) {
|
||||
auto& ni = ctx.nozzle_info;
|
||||
ni.nozzle_list.clear();
|
||||
ni.nozzle_list.push_back({"0.4", NozzleVolumeType::nvtStandard, 0, 0});
|
||||
|
||||
static const NozzleVolumeType vol_types[] = {
|
||||
NozzleVolumeType::nvtStandard, NozzleVolumeType::nvtHighFlow, NozzleVolumeType::nvtTPUHighFlow};
|
||||
|
||||
std::vector<int> ext1_nozzles;
|
||||
for (int i = 0; i < k_nozzles; ++i) {
|
||||
int group_id = i + 1;
|
||||
NozzleVolumeType vt = vol_types[rng.rand_int(0, 2)];
|
||||
ni.nozzle_list.push_back({"0.4", vt, 1, group_id});
|
||||
ext1_nozzles.push_back(group_id);
|
||||
}
|
||||
ni.extruder_nozzle_list = {{0, {0}}, {1, ext1_nozzles}};
|
||||
|
||||
int ext0_max = std::max(4, num_filaments / 2 + 1);
|
||||
int ext1_max = std::max(k_nozzles * 2, num_filaments - ext0_max + 1);
|
||||
ctx.machine_info.max_group_size = {ext0_max, ext1_max};
|
||||
ctx.machine_info.prefer_non_model_filament = {false, false};
|
||||
ctx.machine_info.master_extruder_id = 0;
|
||||
ctx.machine_info.machine_filament_info = generate_machine_filament_info(2, 4, rng);
|
||||
|
||||
ctx.group_info.filament_volume_map.assign(num_filaments, (int)NozzleVolumeType::nvtHybrid);
|
||||
|
||||
ctx.model_info.unprintable_filaments.resize(2);
|
||||
ctx.model_info.flush_matrix.resize(2);
|
||||
for (int ext = 0; ext < 2; ++ext)
|
||||
ctx.model_info.flush_matrix[ext] = generate_flush_matrix(num_filaments, rng);
|
||||
}
|
||||
|
||||
// Config C: 1 extruder, K nozzles (K in [3,9])
|
||||
inline void build_config_c(FilamentGroupContext& ctx, int num_filaments, int k_nozzles, TestRng& rng) {
|
||||
auto& ni = ctx.nozzle_info;
|
||||
ni.nozzle_list.clear();
|
||||
|
||||
static const NozzleVolumeType vol_types[] = {
|
||||
NozzleVolumeType::nvtStandard, NozzleVolumeType::nvtHighFlow,
|
||||
NozzleVolumeType::nvtHybrid, NozzleVolumeType::nvtTPUHighFlow};
|
||||
|
||||
std::vector<int> nozzle_ids;
|
||||
for (int i = 0; i < k_nozzles; ++i) {
|
||||
NozzleVolumeType vt = vol_types[i % 4];
|
||||
ni.nozzle_list.push_back({"0.4", vt, 0, i});
|
||||
nozzle_ids.push_back(i);
|
||||
}
|
||||
ni.extruder_nozzle_list = {{0, nozzle_ids}};
|
||||
|
||||
ctx.machine_info.max_group_size = {num_filaments};
|
||||
ctx.machine_info.prefer_non_model_filament = {false};
|
||||
ctx.machine_info.master_extruder_id = 0;
|
||||
ctx.machine_info.machine_filament_info = generate_machine_filament_info(1, 4, rng);
|
||||
|
||||
ctx.group_info.filament_volume_map.assign(num_filaments, (int)NozzleVolumeType::nvtHybrid);
|
||||
|
||||
ctx.model_info.unprintable_filaments.resize(1);
|
||||
ctx.model_info.flush_matrix.resize(1);
|
||||
ctx.model_info.flush_matrix[0] = generate_flush_matrix(num_filaments, rng);
|
||||
}
|
||||
|
||||
// ============ Constraint Injection ============
|
||||
|
||||
// Add unprintable_filaments constraints (some filaments forbidden on some extruders)
|
||||
inline void inject_unprintable_constraints(FilamentGroupContext& ctx,
|
||||
const std::vector<unsigned int>& used_filaments,
|
||||
TestRng& rng, int num_constraints) {
|
||||
int num_ext = (int)ctx.model_info.unprintable_filaments.size();
|
||||
for (int i = 0; i < num_constraints && !used_filaments.empty(); ++i) {
|
||||
int fil = used_filaments[rng.rand_int(0, (int)used_filaments.size() - 1)];
|
||||
int ext = rng.rand_int(0, num_ext - 1);
|
||||
ctx.model_info.unprintable_filaments[ext].insert(fil);
|
||||
}
|
||||
// Ensure no filament is banned from ALL extruders
|
||||
for (auto fil : used_filaments) {
|
||||
bool can_print_somewhere = false;
|
||||
for (int ext = 0; ext < num_ext; ++ext) {
|
||||
if (!ctx.model_info.unprintable_filaments[ext].count(fil)) {
|
||||
can_print_somewhere = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!can_print_somewhere) {
|
||||
int ext_to_allow = rng.rand_int(0, num_ext - 1);
|
||||
ctx.model_info.unprintable_filaments[ext_to_allow].erase(fil);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add unprintable_volumes constraints
|
||||
inline void inject_volume_constraints(FilamentGroupContext& ctx,
|
||||
const std::vector<unsigned int>& used_filaments,
|
||||
TestRng& rng, int num_constraints) {
|
||||
static const NozzleVolumeType vols[] = {
|
||||
NozzleVolumeType::nvtStandard, NozzleVolumeType::nvtHighFlow,
|
||||
NozzleVolumeType::nvtTPUHighFlow};
|
||||
|
||||
for (int i = 0; i < num_constraints && !used_filaments.empty(); ++i) {
|
||||
int fil = used_filaments[rng.rand_int(0, (int)used_filaments.size() - 1)];
|
||||
NozzleVolumeType vt = vols[rng.rand_int(0, 2)];
|
||||
ctx.model_info.unprintable_volumes[fil].insert(vt);
|
||||
}
|
||||
// Ensure no filament is banned from ALL nozzle volume types present
|
||||
for (auto fil : used_filaments) {
|
||||
if (!ctx.model_info.unprintable_volumes.count(fil))
|
||||
continue;
|
||||
auto& banned = ctx.model_info.unprintable_volumes[fil];
|
||||
bool can_go_somewhere = false;
|
||||
for (auto& noz : ctx.nozzle_info.nozzle_list) {
|
||||
if (!banned.count(noz.volume_type)) {
|
||||
can_go_somewhere = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!can_go_somewhere && !banned.empty()) {
|
||||
// Remove one random ban
|
||||
auto it = banned.begin();
|
||||
std::advance(it, rng.rand_int(0, (int)banned.size() - 1));
|
||||
banned.erase(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Full Case Builder ============
|
||||
|
||||
inline TestCase build_test_case(const std::string& id, const std::string& config_type,
|
||||
int seed, int num_filaments, int num_layers,
|
||||
bool chaotic_layers, bool with_constraints,
|
||||
FGMode mode, FGStrategy strategy, bool group_with_time) {
|
||||
TestRng rng(seed);
|
||||
TestCase tc;
|
||||
tc.metadata.id = id;
|
||||
tc.metadata.config_type = config_type;
|
||||
tc.metadata.seed = seed;
|
||||
|
||||
auto& ctx = tc.context;
|
||||
|
||||
// Used filaments: 0-based indices
|
||||
std::vector<unsigned int> used_filaments;
|
||||
for (int i = 0; i < num_filaments; ++i)
|
||||
used_filaments.push_back((unsigned int)i);
|
||||
|
||||
// Build machine config
|
||||
if (config_type == "A") {
|
||||
build_config_a(ctx, num_filaments, rng);
|
||||
} else if (config_type == "B") {
|
||||
int k = rng.rand_int(2, 6);
|
||||
build_config_b(ctx, num_filaments, k, rng);
|
||||
} else {
|
||||
int k = rng.rand_int(3, 9);
|
||||
build_config_c(ctx, num_filaments, k, rng);
|
||||
}
|
||||
|
||||
// Layer filaments
|
||||
if (chaotic_layers)
|
||||
ctx.model_info.layer_filaments = generate_layer_filaments_chaotic(num_layers, num_filaments, used_filaments, rng);
|
||||
else
|
||||
ctx.model_info.layer_filaments = generate_layer_filaments_interval(num_layers, num_filaments, used_filaments, rng);
|
||||
|
||||
// Filament info
|
||||
ctx.model_info.filament_info = generate_filament_info(num_filaments, rng);
|
||||
ctx.model_info.filament_ids.resize(num_filaments);
|
||||
for (int i = 0; i < num_filaments; ++i)
|
||||
ctx.model_info.filament_ids[i] = "GFL_" + std::to_string(i);
|
||||
|
||||
// Group info
|
||||
ctx.group_info.total_filament_num = num_filaments;
|
||||
ctx.group_info.max_gap_threshold = 0.01;
|
||||
ctx.group_info.mode = mode;
|
||||
ctx.group_info.strategy = strategy;
|
||||
ctx.group_info.ignore_ext_filament = false;
|
||||
ctx.group_info.has_filament_switcher = false;
|
||||
|
||||
// Speed info
|
||||
ctx.speed_info.extruder_change_time = 5.0;
|
||||
ctx.speed_info.filament_change_time = 2.0;
|
||||
ctx.speed_info.group_with_time = group_with_time;
|
||||
ctx.speed_info.change_time_params = {1.0f, 1.0f, 3.0f, 2.0f};
|
||||
int num_ext = (config_type == "C") ? 1 : 2;
|
||||
ctx.speed_info.ams_preload_enabled.assign(num_ext, true);
|
||||
|
||||
// Constraints
|
||||
if (with_constraints) {
|
||||
inject_unprintable_constraints(ctx, used_filaments, rng, rng.rand_int(1, num_filaments / 2));
|
||||
if (config_type != "A")
|
||||
inject_volume_constraints(ctx, used_filaments, rng, rng.rand_int(1, 3));
|
||||
}
|
||||
|
||||
// Nozzle status (initially empty)
|
||||
ctx.nozzle_info.nozzle_status.clear();
|
||||
|
||||
return tc;
|
||||
}
|
||||
|
||||
} // namespace FGTest
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif // FG_TEST_UTILS_HPP
|
||||
330
tests/filament_group/filament_group_regression_main.cpp
Normal file
330
tests/filament_group/filament_group_regression_main.cpp
Normal file
@@ -0,0 +1,330 @@
|
||||
// H2C/A2L FilamentGroup golden regression harness.
|
||||
//
|
||||
// Notes:
|
||||
// * Orca: links Catch2::Catch2WithMain and uses the v3 convenience include <catch2/catch_all.hpp>.
|
||||
// * All three golden families (config_a one-nozzle-per-extruder, config_b/config_c nozzle-centric)
|
||||
// are evaluated against the goldens. The nozzle-centric FilamentGroup engine and solver layer run
|
||||
// the same algorithm the goldens were generated with, scored via the nozzle-aware reorder
|
||||
// (fg_test_evaluator.hpp) at a 3% one-directional tolerance.
|
||||
// * The hidden [update-golden] utility is intentionally omitted: the goldens are the reference
|
||||
// and must not be rewritten from Orca output.
|
||||
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "fg_test_serialization.hpp"
|
||||
#include "fg_test_evaluator.hpp"
|
||||
#include "fg_test_utils.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <numeric>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::FGTest;
|
||||
|
||||
// ============ Helpers ============
|
||||
|
||||
static std::vector<std::string> collect_test_files(const std::string& dir) {
|
||||
std::vector<std::string> files;
|
||||
if (!fs::exists(dir)) return files;
|
||||
for (auto& entry : fs::recursive_directory_iterator(dir)) {
|
||||
if (entry.path().extension() == ".json" &&
|
||||
entry.path().string().find(".result.") == std::string::npos) {
|
||||
files.push_back(entry.path().string());
|
||||
}
|
||||
}
|
||||
std::sort(files.begin(), files.end());
|
||||
return files;
|
||||
}
|
||||
|
||||
static std::vector<std::string> get_golden_files() {
|
||||
static std::vector<std::string> files = collect_test_files(FG_TEST_GOLDEN_DIR);
|
||||
return files;
|
||||
}
|
||||
|
||||
static bool is_constraint_feasible(const FilamentGroupContext& ctx,
|
||||
const std::vector<unsigned int>& used_filaments) {
|
||||
int total_capacity = 0;
|
||||
for (auto sz : ctx.machine_info.max_group_size)
|
||||
total_capacity += sz;
|
||||
if (total_capacity < (int)used_filaments.size())
|
||||
return false;
|
||||
|
||||
// Check that every filament has at least one valid nozzle
|
||||
for (auto fil : used_filaments) {
|
||||
bool has_valid_nozzle = false;
|
||||
for (size_t nid = 0; nid < ctx.nozzle_info.nozzle_list.size(); ++nid) {
|
||||
auto& nozzle = ctx.nozzle_info.nozzle_list[nid];
|
||||
// Check unprintable_filaments
|
||||
if (nozzle.extruder_id >= 0 && nozzle.extruder_id < (int)ctx.model_info.unprintable_filaments.size()) {
|
||||
if (ctx.model_info.unprintable_filaments[nozzle.extruder_id].count(fil))
|
||||
continue;
|
||||
}
|
||||
// Check unprintable_volumes
|
||||
if (ctx.model_info.unprintable_volumes.count(fil)) {
|
||||
if (ctx.model_info.unprintable_volumes.at(fil).count(nozzle.volume_type))
|
||||
continue;
|
||||
}
|
||||
has_valid_nozzle = true;
|
||||
break;
|
||||
}
|
||||
if (!has_valid_nozzle)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ============ Property Check Specs ============
|
||||
|
||||
struct PropertySpec {
|
||||
std::string id;
|
||||
std::string config;
|
||||
int seed;
|
||||
int num_filaments;
|
||||
int num_layers;
|
||||
bool chaotic;
|
||||
bool with_constraints;
|
||||
FGMode mode;
|
||||
FGStrategy strategy;
|
||||
bool group_with_time;
|
||||
};
|
||||
|
||||
static std::vector<PropertySpec> build_property_specs() {
|
||||
std::vector<PropertySpec> specs;
|
||||
|
||||
// Config A: 20 cases
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
int seed = 90000 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_a_basic_" + std::to_string(i), "A", seed,
|
||||
rng.rand_int(2, 6), rng.rand_int(100, 400),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
int seed = 90100 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_a_stress_" + std::to_string(i), "A", seed,
|
||||
rng.rand_int(7, 10), rng.rand_int(500, 1000),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
int seed = 90200 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_a_constraint_" + std::to_string(i), "A", seed,
|
||||
rng.rand_int(3, 8), rng.rand_int(100, 400),
|
||||
false, true, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
int seed = 90300 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_a_edge_" + std::to_string(i), "A", seed,
|
||||
rng.rand_int(2, 3), rng.rand_int(10, 50),
|
||||
true, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
specs.push_back({"prop_a_mode_match", "A", 90400,
|
||||
5, 200, false, false, FGMode::MatchMode, FGStrategy::BestCost, false});
|
||||
specs.push_back({"prop_a_mode_bestfit", "A", 90401,
|
||||
5, 200, false, false, FGMode::FlushMode, FGStrategy::BestFit, false});
|
||||
specs.push_back({"prop_a_mode_time", "A", 90402,
|
||||
5, 200, false, false, FGMode::FlushMode, FGStrategy::BestCost, true});
|
||||
|
||||
// Config B: 25 cases
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
int seed = 91000 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_b_basic_" + std::to_string(i), "B", seed,
|
||||
rng.rand_int(3, 8), rng.rand_int(100, 400),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
int seed = 91100 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_b_stress_" + std::to_string(i), "B", seed,
|
||||
rng.rand_int(9, 12), rng.rand_int(500, 1000),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
int seed = 91200 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_b_constraint_" + std::to_string(i), "B", seed,
|
||||
rng.rand_int(4, 10), rng.rand_int(100, 400),
|
||||
false, true, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
int seed = 91300 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_b_edge_" + std::to_string(i), "B", seed,
|
||||
rng.rand_int(2, 4), rng.rand_int(10, 50),
|
||||
true, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
specs.push_back({"prop_b_mode_match", "B", 91400,
|
||||
6, 200, false, false, FGMode::MatchMode, FGStrategy::BestCost, false});
|
||||
specs.push_back({"prop_b_mode_bestfit", "B", 91401,
|
||||
6, 200, false, false, FGMode::FlushMode, FGStrategy::BestFit, false});
|
||||
specs.push_back({"prop_b_mode_time", "B", 91402,
|
||||
6, 200, false, false, FGMode::FlushMode, FGStrategy::BestCost, true});
|
||||
|
||||
// Config C: 15 cases
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
int seed = 92000 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_c_basic_" + std::to_string(i), "C", seed,
|
||||
rng.rand_int(3, 9), rng.rand_int(100, 400),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
int seed = 92100 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_c_stress_" + std::to_string(i), "C", seed,
|
||||
rng.rand_int(10, 15), rng.rand_int(500, 1000),
|
||||
false, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
int seed = 92200 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_c_constraint_" + std::to_string(i), "C", seed,
|
||||
rng.rand_int(4, 9), rng.rand_int(100, 400),
|
||||
false, true, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
int seed = 92300 + i;
|
||||
TestRng rng(seed);
|
||||
specs.push_back({"prop_c_edge_" + std::to_string(i), "C", seed,
|
||||
rng.rand_int(2, 4), rng.rand_int(10, 50),
|
||||
true, false, FGMode::FlushMode, FGStrategy::BestCost, false});
|
||||
}
|
||||
specs.push_back({"prop_c_mode_match", "C", 92400,
|
||||
6, 200, false, false, FGMode::MatchMode, FGStrategy::BestCost, false});
|
||||
specs.push_back({"prop_c_mode_bestfit", "C", 92401,
|
||||
6, 200, false, false, FGMode::FlushMode, FGStrategy::BestFit, false});
|
||||
|
||||
return specs;
|
||||
}
|
||||
|
||||
static std::vector<PropertySpec>& get_property_specs() {
|
||||
static std::vector<PropertySpec> specs = build_property_specs();
|
||||
return specs;
|
||||
}
|
||||
|
||||
// Under the default wall clock the result depends on how fast the machine is (see ClusteringBudget),
|
||||
// so the goldens are graded under a fixed budget instead. Two restarts is the fewest that reaches
|
||||
// parity with the reference on every golden, stress_79 being the last to get there. Four leaves
|
||||
// margin, since the search follows a different path on each standard library (see below).
|
||||
static constexpr ClusteringBudget FIXED_SEARCH_BUDGET{
|
||||
/*timeout_ms*/ 0, // no wall clock
|
||||
/*max_restarts*/ 4};
|
||||
|
||||
// ============ Layer 1: Golden Regression (all configs) ============
|
||||
|
||||
// Graded against the BambuStudio golden the harness was ported from, one-directional at 3%.
|
||||
//
|
||||
// The tolerance is a parity allowance, and it also covers a small spread across standard libraries.
|
||||
// The k-medoids search seeds each restart with std::shuffle, whose algorithm the C++ standard leaves
|
||||
// unspecified, so libstdc++, libc++ and the MSVC STL permute the same seed differently, start from
|
||||
// different medoids, and settle on slightly different groupings, about 3e-4 apart on either side of
|
||||
// the reference, and only on the goldens heavy enough to reach the k-medoids search.
|
||||
TEST_CASE("FilamentGroup golden regression", "[filament_group][golden]") {
|
||||
auto files = get_golden_files();
|
||||
if (files.empty()) {
|
||||
WARN("No golden files found in " FG_TEST_GOLDEN_DIR);
|
||||
REQUIRE(!files.empty());
|
||||
return;
|
||||
}
|
||||
|
||||
auto file_path = GENERATE_REF(from_range(files));
|
||||
|
||||
DYNAMIC_SECTION("Golden: " << fs::path(file_path).stem().string()) {
|
||||
auto tc = load_test_case(file_path);
|
||||
REQUIRE(tc.base_result.has_value());
|
||||
|
||||
auto result = run_and_evaluate(tc.context, FIXED_SEARCH_BUDGET);
|
||||
auto eval = full_evaluate_map(tc.context, result.filament_map);
|
||||
|
||||
auto& base = *tc.base_result;
|
||||
|
||||
INFO("Case: " << tc.metadata.id);
|
||||
INFO("Golden score: " << base.full_score);
|
||||
INFO("Actual score: " << eval.full_score);
|
||||
INFO("Flush cost: " << eval.flush_cost << " (golden " << base.flush_cost << ")");
|
||||
INFO("Elapsed: " << result.elapsed_ms << " ms");
|
||||
|
||||
int tolerance = std::max(50, (int)(base.full_score * 0.03));
|
||||
|
||||
REQUIRE(result.constraints_ok);
|
||||
REQUIRE(eval.full_score <= base.full_score + tolerance);
|
||||
|
||||
// A slower search still scores the same above, since it searches just as far, but in slicing
|
||||
// it would mean fewer restarts fit in the wall clock and so worse groupings. Loose on
|
||||
// purpose, so it never becomes a proxy for how loaded the runner is.
|
||||
const double throughput_ceiling_ms = 10.0 * ClusteringBudget{}.timeout_ms;
|
||||
REQUIRE(result.elapsed_ms < throughput_ceiling_ms);
|
||||
}
|
||||
}
|
||||
|
||||
// Covers the path real slicing takes, under the default wall clock. The score there depends on the
|
||||
// runner rather than on the code (see FIXED_SEARCH_BUDGET), so the only things worth asserting are
|
||||
// that the grouping comes back valid and that the search terminates.
|
||||
TEST_CASE("FilamentGroup returns a valid grouping under the default budget", "[filament_group][budget]") {
|
||||
auto files = get_golden_files();
|
||||
REQUIRE(!files.empty());
|
||||
|
||||
auto file_path = GENERATE_REF(from_range(files));
|
||||
|
||||
DYNAMIC_SECTION("Golden: " << fs::path(file_path).stem().string()) {
|
||||
auto tc = load_test_case(file_path);
|
||||
|
||||
auto result = run_and_evaluate(tc.context); // the default budget, as real slicing runs it
|
||||
|
||||
INFO("Case: " << tc.metadata.id);
|
||||
INFO("Elapsed: " << result.elapsed_ms << " ms");
|
||||
|
||||
REQUIRE(result.constraints_ok);
|
||||
// A hang guard. The clock is only checked between swaps, so a sweep can overshoot.
|
||||
REQUIRE(result.elapsed_ms < 40000.0);
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Layer 2: Property Checks (all configs) ============
|
||||
|
||||
TEST_CASE("FilamentGroup property checks", "[filament_group][property]") {
|
||||
auto& specs = get_property_specs();
|
||||
auto spec = GENERATE_REF(from_range(specs));
|
||||
|
||||
DYNAMIC_SECTION("Property: " << spec.id) {
|
||||
auto tc = build_test_case(spec.id, spec.config, spec.seed,
|
||||
spec.num_filaments, spec.num_layers,
|
||||
spec.chaotic, spec.with_constraints,
|
||||
spec.mode, spec.strategy, spec.group_with_time);
|
||||
|
||||
auto result = run_and_evaluate(tc.context);
|
||||
|
||||
INFO("Case: " << spec.id);
|
||||
INFO("Config: " << spec.config);
|
||||
INFO("Flush cost: " << result.flush_cost);
|
||||
INFO("Elapsed: " << result.elapsed_ms << " ms");
|
||||
|
||||
// RelWithDebInfo runaway guard; the Release-calibrated 10 s limit is raised for the slower
|
||||
// build (config_b/config_c cases evaluate the full per-layer nozzle-aware reorder for every
|
||||
// candidate grouping; this is a guard against hangs, not a micro-perf gate).
|
||||
REQUIRE(result.elapsed_ms < 40000.0);
|
||||
REQUIRE(result.flush_cost >= 0);
|
||||
|
||||
auto used_filaments = collect_sorted_used_filaments(tc.context.model_info.layer_filaments);
|
||||
if (is_constraint_feasible(tc.context, used_filaments)) {
|
||||
if (!result.constraints_ok) {
|
||||
for (auto& v : result.violations)
|
||||
WARN("Violation: " << v);
|
||||
}
|
||||
REQUIRE(result.constraints_ok);
|
||||
} else {
|
||||
if (!result.constraints_ok) {
|
||||
WARN("Constraint violation (infeasible case, soft): " << spec.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1
tests/filament_group/golden/config_a/basic_17.json
Normal file
1
tests/filament_group/golden/config_a/basic_17.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":4.0},"context":{"group_info":{"filament_volume_map":[2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":2},"machine_info":{"machine_filament_info":[[{"color":"#850C02FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#F10331FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#429A7CFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#8D67FEFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#2677E2FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#3A3922FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#DB8EB9FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#53A5A6FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[2,2],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1"],"filament_info":[{"color":"#E8650CFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#0A9E99FF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,18.864795684814453],[512.7918701171875,0.0]],[[0.0,332.1666259765625],[58.37631607055664,0.0]]],"layer_filaments":[[0,1],[0,1],[0,1],[1],[0,1],[0,1],[0,1],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[1],[1],[0],[0],[0],[0],[0],[0],[0],[0],[1],[1],[1],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[1],[0],[0,1],[0],[0],[0],[0,1],[0,1],[0,1],[0],[0],[1],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0],[0],[0,1],[0,1],[1],[1],[1],[1],[1],[0],[0],[0,1],[1],[0],[0,1],[1],[0],[0],[0,1],[0],[0],[0],[0,1],[0,1],[1],[0,1],[0],[0],[0],[0,1],[1],[1],[1],[1],[0,1],[0,1],[1],[0,1],[0,1],[0],[0],[0],[0],[0],[0,1],[1]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_basic_17","seed":10017}}
|
||||
1
tests/filament_group/golden/config_a/basic_39.json
Normal file
1
tests/filament_group/golden/config_a/basic_39.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":4.0},"context":{"group_info":{"filament_volume_map":[2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":2},"machine_info":{"machine_filament_info":[[{"color":"#3C6B30FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FE9954FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FBBAB3FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A1A591FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#55EE36FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A8F42BFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#930D0FFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#55C501FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[2,2],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1"],"filament_info":[{"color":"#C613F1FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#0C0CBAFF","is_support":false,"type":"PLA","usage_type":1}],"flush_matrix":[[[0.0,463.53955078125],[50.04071044921875,0.0]],[[0.0,54.75393295288086],[566.574951171875,0.0]]],"layer_filaments":[[0,1],[0],[0],[0,1],[0,1],[0,1],[0],[0],[0,1],[1],[1],[1],[1],[0,1],[0,1],[0],[0],[0],[0],[0],[1],[1],[0,1],[0,1],[1],[0,1],[0],[0],[0],[0],[0,1],[1],[0],[0],[0],[0,1],[0,1],[0,1],[1],[1],[1],[1],[1],[0,1],[0],[0,1],[0,1],[0,1],[1],[1],[1],[0,1],[0,1],[1],[0],[0,1],[1],[0],[0],[1],[0,1],[1],[1],[1],[0,1],[0,1],[0],[0],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0,1],[1],[0,1],[1],[0],[0],[1],[0,1],[0,1],[1],[0,1],[0,1],[1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[1],[1],[0,1],[0,1],[0,1],[0],[0],[0,1],[1],[1],[1],[0,1],[1],[0,1],[0,1],[1],[1],[1],[0],[0],[0],[1],[1],[0,1],[1],[1],[0,1],[0],[0],[1],[0,1],[1],[0,1],[1],[1],[0],[0,1],[0,1],[0,1],[1],[1],[0,1],[0,1],[0,1],[1],[0,1],[0],[0,1],[0,1],[0],[0],[1],[1],[0,1],[0,1],[0,1],[0,1],[1],[1],[1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0,1],[1],[0],[0],[1],[1],[0],[0],[0,1],[0],[0],[0],[0,1],[0],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[1],[0],[0,1],[0],[0,1],[0,1],[0,1],[0,1],[1],[0,1],[0,1],[0,1],[0,1],[1],[1],[1],[0,1],[1],[0,1],[0,1],[0,1],[0,1],[0],[0],[1],[0,1],[0,1],[1],[1],[1],[1],[0],[0],[0],[0],[0],[0],[0],[0],[0],[0,1],[1],[1],[1],[1],[0],[0],[0],[0,1],[0,1],[0],[0,1],[0,1],[0,1]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_basic_39","seed":10039}}
|
||||
1
tests/filament_group/golden/config_a/basic_9.json
Normal file
1
tests/filament_group/golden/config_a/basic_9.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":4.0},"context":{"group_info":{"filament_volume_map":[2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":2},"machine_info":{"machine_filament_info":[[{"color":"#835F29FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#ACB239FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#5EF84BFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FE36A8FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#7B6ABDFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#4FFBDDFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#E06DDEFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#751104FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[2,2],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1"],"filament_info":[{"color":"#48BC3DFF","is_support":false,"type":"PETG","usage_type":1},{"color":"#1DEED1FF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,523.2988891601563],[480.04058837890625,0.0]],[[0.0,18.886493682861328],[47.65232467651367,0.0]]],"layer_filaments":[[0,1],[0],[0,1],[1],[0],[0],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[1],[0,1],[0],[0],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[1],[1],[0],[0],[1],[1],[1],[0],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[0,1],[0,1],[0,1],[0],[1],[0],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[1],[0],[0],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[0],[0],[0],[0],[0],[0],[0,1],[0,1],[0],[0],[1],[0,1],[0],[0],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0],[0],[1],[1],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[1],[1],[0],[0],[0],[0],[0],[0,1],[0],[0,1],[0,1],[0],[0],[0],[0],[0],[1],[1],[0,1],[0,1],[0,1],[1],[1],[1],[1],[1],[1],[0,1],[0,1],[0,1],[1],[1],[0,1],[0,1],[1],[1],[1],[0,1],[0,1],[0,1],[0,1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0,1],[0,1],[0],[1],[1],[1],[1],[1],[1],[0,1],[0,1],[0,1],[1],[1],[0,1],[1],[0,1],[0,1],[0],[0,1],[0,1],[0,1],[0],[1],[0,1],[0,1],[1],[1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[1],[0,1],[1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0,1],[0],[0,1],[1],[0,1],[0,1],[1],[1],[0,1],[0,1],[0,1],[0,1],[0],[0,1],[0],[0,1],[0,1],[0,1],[0,1],[0,1],[0],[0],[0,1],[0,1],[0,1]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_basic_9","seed":10009}}
|
||||
1
tests/filament_group/golden/config_a/constraint_117.json
Normal file
1
tests/filament_group/golden/config_a/constraint_117.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":9996,"full_score":4878.185600000001},"context":{"group_info":{"filament_volume_map":[2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":3},"machine_info":{"machine_filament_info":[[{"color":"#862B28FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#5DE136FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#B737ACFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#AB25E0FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#03D322FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FEF6E8FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#6ACCEDFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#5F679DFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[2,2],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2"],"filament_info":[{"color":"#D4E014FF","is_support":false,"type":"PA","usage_type":1},{"color":"#D01CEEFF","is_support":false,"type":"PA","usage_type":1},{"color":"#E433C7FF","is_support":false,"type":"TPU","usage_type":1}],"flush_matrix":[[[0.0,345.6607360839844,334.3067626953125],[167.5570526123047,0.0,469.119140625],[205.99964904785156,536.2994384765625,0.0]],[[0.0,16.684810638427734,322.7650146484375],[260.761962890625,0.0,230.73336791992188],[267.0419616699219,64.71019744873047,0.0]]],"layer_filaments":[[0,2],[0,1],[0],[1],[1],[1],[1],[1],[1],[1],[1,2],[0,1,2],[0],[2],[1],[1],[1],[1],[1,2],[1,2],[1],[0,1],[0,1],[1,2],[1,2],[1,2],[1,2],[1,2],[2],[0],[1,2],[1,2],[1],[0,2],[0,1,2],[0,1,2],[1],[1,2],[1,2],[1,2],[1,2],[0,1,2],[2],[1],[0,1],[0,1,2],[0,1,2],[0,1,2],[0,2],[0,2],[0,2],[0,2],[0,1,2],[0,1,2],[0,1,2],[2],[2],[2],[1],[0,1],[0,1],[1],[1,2],[1,2],[0,1],[0,1,2],[0,1],[1],[2],[1,2],[2],[2],[2],[2],[2],[1,2],[2],[2],[0,2],[0,1],[0,1],[0,1],[0],[0,1],[0,1],[1],[1],[1],[0],[0,2],[2],[2],[2],[2],[0,2],[1],[1,2],[1],[1],[1],[1],[1],[0,1],[0,1],[0,1],[1],[2],[2],[0],[0],[0],[0],[0,2],[1,2],[0,2],[0,2],[0,2],[0],[1],[1,2],[0,2],[2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[2],[1,2],[2],[0,2],[0,2],[0,2],[0],[0],[0],[0,2],[2],[2],[0,2],[2],[0,1],[0],[0],[0],[0],[0],[1,2],[0,1,2],[0,1,2],[0,1],[1],[1],[0],[0],[0],[0],[1],[1],[1],[0,2],[0,2],[0],[0],[1,2],[1,2]],"unprintable_filaments":[[2],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_constraint_117","seed":10117}}
|
||||
1
tests/filament_group/golden/config_a/constraint_87.json
Normal file
1
tests/filament_group/golden/config_a/constraint_87.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":15640,"full_score":7498.304000000001},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":5},"machine_info":{"machine_filament_info":[[{"color":"#690A58FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#13D9ACFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#255B88FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#14AD07FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#E1E180FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A69E85FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#9F27DAFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#96A697FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[3,3],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4"],"filament_info":[{"color":"#84C1C1FF","is_support":false,"type":"PLA","usage_type":1},{"color":"#1EB5C4FF","is_support":false,"type":"PLA","usage_type":1},{"color":"#8D50E5FF","is_support":false,"type":"PETG","usage_type":1},{"color":"#F22BC4FF","is_support":false,"type":"PA","usage_type":1},{"color":"#B7A86EFF","is_support":false,"type":"PA","usage_type":1}],"flush_matrix":[[[0.0,494.378173828125,256.524658203125,43.245582580566406,405.5243835449219],[16.6104679107666,0.0,150.26849365234375,400.1143493652344,30.314559936523438],[24.301469802856445,130.10775756835938,0.0,536.2122192382813,383.1336669921875],[437.3901062011719,272.96868896484375,82.35665893554688,0.0,17.11191177368164],[468.4289245605469,355.7682800292969,452.1650085449219,45.59552764892578,0.0]],[[0.0,491.8825378417969,205.77655029296875,349.1083984375,506.652099609375],[101.32499694824219,0.0,175.80380249023438,120.50504302978516,438.80804443359375],[152.76100158691406,355.5727233886719,0.0,581.8612060546875,585.173583984375],[546.7792358398438,22.963092803955078,407.84173583984375,0.0,105.83439636230469],[356.05926513671875,145.5247344970703,230.94595336914063,345.7974548339844,0.0]]],"layer_filaments":[[0,3,4],[0],[0],[0],[0],[0],[4],[4],[1],[1],[1],[3],[1],[1],[3],[0,1,4],[0,1],[0,1,3],[0,1],[1],[0],[0,3],[0,3],[2],[3,4],[0,2],[2,4],[4],[3],[3],[3],[1],[2],[4],[4],[4],[4],[0,3,4],[0,3],[0,3,4],[0,4],[0,3,4],[0,2,3],[0,2],[0,2],[0,2],[0,2],[0],[0],[0],[0,3,4],[3,4],[1,3,4],[3,4],[3,4],[3],[2],[4],[4],[4],[4],[4],[1],[1],[1],[1],[1],[1,4],[1],[1,3],[2,3],[2,3,4],[2,3,4],[3,4],[3,4],[0,1,3],[0,1],[0,1],[0,1,2],[0,1,2],[1,2],[1,2],[1,2],[0,2,3],[0,2,3],[0,2,3],[3],[3],[0,3,4],[0,2,3,4],[0,2,3,4],[0,2,3],[2],[2],[2],[0],[1],[1],[1],[4],[1,4],[0,4],[0,3,4],[0,3,4],[0,3,4],[0,3,4],[0,3,4],[0,3,4],[3],[3],[3],[0,3],[0,3],[0],[4],[3,4]],"unprintable_filaments":[[],[0,1]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_constraint_87","seed":10087}}
|
||||
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":22348,"full_score":10641.052800000001},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":1,"total_filament_num":7},"machine_info":{"machine_filament_info":[[{"color":"#CA0BBFFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#04BBE7FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#0C9192FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#D03AE7FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#58ED4CFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#F0F7E7FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#C01A00FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#41BF7EFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4","GFL_5","GFL_6"],"filament_info":[{"color":"#15D1F3FF","is_support":false,"type":"PETG","usage_type":1},{"color":"#2E765BFF","is_support":false,"type":"TPU","usage_type":1},{"color":"#F7F661FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#1F8FA4FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#548538FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#49CDDAFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#77400CFF","is_support":false,"type":"TPU","usage_type":1}],"flush_matrix":[[[0.0,522.1661987304688,100.72758483886719,133.01226806640625,491.89971923828125,10.22260570526123,398.2569580078125],[199.46890258789063,0.0,193.49847412109375,173.7811737060547,254.3165283203125,524.8251342773438,11.158357620239258],[25.300485610961914,185.6349334716797,0.0,14.763650894165039,527.9827270507813,503.7408142089844,196.4144287109375],[14.506301879882813,388.3427429199219,592.0447387695313,0.0,43.87137222290039,568.1431274414063,473.7308654785156],[320.220703125,309.9248352050781,39.37203598022461,47.134002685546875,0.0,97.27034759521484,458.011962890625],[572.5841674804688,336.4319152832031,47.922828674316406,278.3333740234375,182.32958984375,0.0,402.6477966308594],[447.379150390625,588.4238891601563,13.493745803833008,433.3789978027344,390.13360595703125,461.5366516113281,0.0]],[[0.0,298.9002380371094,586.3795776367188,271.62158203125,272.1965637207031,152.54571533203125,239.88775634765625],[99.5313949584961,0.0,165.59657287597656,83.9988021850586,219.39901733398438,418.60491943359375,575.6079711914063],[35.19260787963867,44.58149719238281,0.0,212.56053161621094,139.3209686279297,596.1610107421875,564.784423828125],[488.8506774902344,419.78521728515625,321.46514892578125,0.0,46.86149597167969,310.4212341308594,303.2931213378906],[531.5128173828125,116.25019073486328,207.16612243652344,50.03121566772461,0.0,385.4001770019531,108.3058090209961],[497.9175720214844,444.3203125,331.2178649902344,499.4423828125,546.33642578125,0.0,352.6327209472656],[423.0767822265625,189.04090881347656,132.35194396972656,453.5607604980469,29.324968338012695,336.557861328125,0.0]]],"layer_filaments":[[0,3,4,5],[0,4,5],[0,1,4,5],[1,4,5],[1,5],[4],[4],[5],[5],[5],[5],[6],[1],[1],[1,3],[1,3],[0,1,3],[0,3,4,5],[1,4,5],[1,4],[3,4],[0,1],[0,1],[0,1],[0,1],[1,5],[1,5],[1],[1],[1],[4],[4],[3,4],[0,1,6],[0,1,6],[1,3,6],[1,3,6],[6],[6],[3,6],[3,6],[3,6],[0,3,4,5],[0,3,4,5],[0,2,3,4,5],[0,2,3],[0,3],[0,3],[0,3],[0],[0,4],[4],[2,3,4,6],[2,4],[2,4],[5],[5],[5],[5],[2,5],[2,3,5],[2,3,5],[2,3,5],[2],[2,3,4],[2,3,4],[0,3,4],[0,3,4],[3,4,6],[0,3,4,6],[0,3,6],[0,3,6],[1,3,4,5],[0,3],[1,3,5,6],[5,6],[4,5,6],[3,4],[3],[1,3],[3],[2,3,5,6],[3,5,6],[5],[2],[6],[6],[4,6],[6],[6],[4,6],[1,4,6],[4],[0],[0],[0,5],[5],[6],[0,1],[0,1],[0,1,3],[0],[0],[0],[0,3],[0,3],[0,3],[0,3,5],[3,5],[3],[3],[3],[3],[3,5],[3,5],[0,3,5],[0]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_mode_bestfit_161","seed":10161}}
|
||||
1
tests/filament_group/golden/config_a/mode_match_150.json
Normal file
1
tests/filament_group/golden/config_a/mode_match_150.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":28788,"full_score":13492.236799999999},"context":{"group_info":{"filament_volume_map":[2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":1,"strategy":0,"total_filament_num":4},"machine_info":{"machine_filament_info":[[{"color":"#2C1334FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#672D31FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#40C111FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#0D6A9EFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#1C9D92FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#DFD03AFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#9F1CE2FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#3F8A30FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[3,3],"prefer_non_model_filament":[false,true]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3"],"filament_info":[{"color":"#3F3A9BFF","is_support":false,"type":"TPU","usage_type":1},{"color":"#2A420FFF","is_support":false,"type":"TPU","usage_type":1},{"color":"#37A850FF","is_support":false,"type":"PETG","usage_type":1},{"color":"#EB9B49FF","is_support":false,"type":"PA","usage_type":1}],"flush_matrix":[[[0.0,357.30389404296875,131.00808715820313,575.68603515625],[289.8275451660156,0.0,56.926780700683594,548.9874877929688],[323.252685546875,156.2064666748047,0.0,210.6259002685547],[469.44366455078125,165.70809936523438,174.34884643554688,0.0]],[[0.0,141.2342529296875,146.28591918945313,193.52146911621094],[548.3370971679688,0.0,404.035400390625,559.38232421875],[110.14042663574219,127.97674560546875,0.0,582.9161376953125],[221.37879943847656,321.6277160644531,375.734619140625,0.0]]],"layer_filaments":[[0,1,2],[0],[0],[1],[1],[1],[1],[1,3],[2],[2],[2],[0],[0,1,2],[1,2],[2],[2],[2],[2],[2],[3],[0,3],[0,3],[0,2],[2],[1,2],[1,2],[1],[0,1,2],[0,1],[0,1],[1,3],[0,1,3],[0,1,3],[0],[0,2],[0],[0],[0],[0],[0],[0,1,2],[0,1,3],[1,3],[1,3],[1,3],[1,3],[1,2,3],[0,1,2,3],[1,2,3],[0,1,2],[0,1,2],[0,1],[0,1],[0,1],[0,1,2],[0,1,2],[0,1,2,3],[0,1,2,3],[0,1],[1,2,3],[1,2],[0],[1,3],[0],[0],[2],[2,3],[1,2],[2],[1,2],[0,1],[1],[1,2],[1],[0,3],[0,3],[1,3],[1,3],[1,3],[1,3],[1],[1],[1],[1],[1],[1],[1],[1],[0,2],[0,2],[0,2,3],[1,2],[1,2],[1,2],[2],[2],[2],[2],[1,3],[1],[1],[1],[2,3],[2],[2],[2],[2],[2],[2],[2],[0,1],[0,2,3],[0,2,3],[0,2],[0,2],[0,2],[0],[1,3],[1,3],[3],[1,3],[0,3],[0,2,3],[0,2,3],[0,2,3],[3],[3],[3],[2],[1,2]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"A","id":"A_mode_match_150","seed":10150}}
|
||||
1
tests/filament_group/golden/config_a/mode_time_164.json
Normal file
1
tests/filament_group/golden/config_a/mode_time_164.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_a/stress_55.json
Normal file
1
tests/filament_group/golden/config_a/stress_55.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_a/stress_68.json
Normal file
1
tests/filament_group/golden/config_a/stress_68.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_b/basic_24.json
Normal file
1
tests/filament_group/golden/config_b/basic_24.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":184.0},"context":{"group_info":{"filament_volume_map":[2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":3},"machine_info":{"machine_filament_info":[[{"color":"#58191BFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#65BA4BFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#8198CBFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#ACC0ABFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#22ED52FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#C09D59FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#2DA502FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#F7A2FAFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2"],"filament_info":[{"color":"#D0206DFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#8F4679FF","is_support":false,"type":"PA","usage_type":1},{"color":"#29B62DFF","is_support":false,"type":"ABS","usage_type":1}],"flush_matrix":[[[0.0,22.997100830078125,311.9136962890625],[467.8121032714844,0.0,309.3307189941406],[409.413330078125,543.3587646484375,0.0]],[[0.0,424.8780517578125,513.323974609375],[432.9106750488281,0.0,186.18800354003906],[419.3179016113281,409.17095947265625,0.0]]],"layer_filaments":[[0,1],[0,2],[0],[0,1],[0,1,2],[1],[1],[1],[1],[2],[0],[0,2],[0],[0],[0,2],[0,1],[0],[2],[2],[2],[2],[2],[2],[1,2],[1,2],[1],[2],[2],[0,1],[0,2],[1,2],[1],[1],[0,1],[0,1,2],[2],[2],[2],[1],[1],[2],[2],[0],[1],[0],[0,1],[0,1],[0,1],[1],[1],[1],[0,1],[1,2],[0,1,2],[1,2],[1,2],[1,2],[1,2],[0,2],[0,1],[0,1],[1,2],[1],[1],[2],[2],[2],[2],[1,2],[1],[1],[1],[1],[0],[0],[2],[0,2],[0,1,2],[2],[2],[2],[0,2],[0,1,2],[0,2],[2],[1],[1],[1],[2],[2],[2],[1,2],[1,2],[2],[2],[2],[0,2],[0,2],[2],[0,2],[0],[0],[0],[0,1],[0,1],[0,1],[0,1],[0,2],[0,2],[0],[0,2],[2],[1,2],[2],[1,2],[0,2],[0],[0,2],[1],[1],[1],[2],[0,1]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_basic_24","seed":20024}}
|
||||
1
tests/filament_group/golden/config_b/basic_27.json
Normal file
1
tests/filament_group/golden/config_b/basic_27.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":439.0},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":5},"machine_info":{"machine_filament_info":[[{"color":"#CE9589FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#C1CA1FFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#63C10EFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#1FB0EDFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#D1526EFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FFFDCCFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FE458BFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FE7A24FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,8],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4"],"filament_info":[{"color":"#E892ACFF","is_support":false,"type":"PETG","usage_type":1},{"color":"#9BF6B9FF","is_support":false,"type":"ABS","usage_type":1},{"color":"#B37CAAFF","is_support":false,"type":"PETG","usage_type":1},{"color":"#E57574FF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#4821E8FF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,375.2281494140625,463.1433410644531,91.72261810302734,543.7777709960938],[40.411563873291016,0.0,46.204158782958984,133.43045043945313,140.9217987060547],[385.8175354003906,90.685302734375,0.0,140.52508544921875,75.50867462158203],[316.38568115234375,89.43927764892578,424.980224609375,0.0,27.291486740112305],[50.60981369018555,200.03822326660156,547.7901000976563,466.6471862792969,0.0]],[[0.0,240.17831420898438,577.3026123046875,222.15658569335938,590.8341064453125],[424.3199157714844,0.0,434.2823486328125,209.71908569335938,437.5057373046875],[349.07037353515625,464.85870361328125,0.0,32.95913314819336,527.3640747070313],[256.4498596191406,298.9818115234375,598.7887573242188,0.0,31.422487258911133],[529.8190307617188,558.2802734375,43.493682861328125,432.5175476074219,0.0]]],"layer_filaments":[[1,2,4],[1,2,4],[1,4],[1,4],[4],[4],[2],[2,4],[2,4],[2,4],[2,3],[1,2,3],[2,3],[2,3],[3],[3],[0,4],[0,4],[0,4],[0],[0],[0,3],[0,2,3],[2],[2],[1,2],[1,2],[0,2],[0,2],[0,2],[0],[0,2,4],[0,2,4],[0,1,3],[0,1,3,4],[0,1,2,3],[0,1,2,3],[2,3],[1,2,3],[1,2],[2],[3],[0,2,4],[0,4],[0,4],[1,4],[0,1,4],[0,1,4],[0,4],[4],[4],[4],[3],[3],[3],[0,1,4],[2],[0,2],[0,2],[0,2,4],[0,1,2],[0,1],[0,1],[1],[1],[1],[1],[3],[3],[3],[4],[3,4],[3,4],[4],[4],[4],[4],[4],[2],[2],[2],[2,4],[2,3,4],[3],[0,2,4],[0],[0],[1],[1],[2],[2],[2],[1],[1],[0,1],[0,1,2],[0,2],[1,3],[1,3],[1,3],[0,1],[0,1,3],[0,1,3,4],[0,1,3],[0,3],[3],[2,3],[2],[2],[2],[1],[3],[2,3],[1,3],[3],[3],[2],[2,4],[0,3,4],[3,4],[3],[0,3,4],[0,4],[3,4],[2,3],[1,2],[1,2],[1,2],[1,2],[1,2],[2],[2],[1,2],[1,2]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2,3,4]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":1},{"diameter":"0.4","extruder_id":1,"group_id":3,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":4,"volume_type":3}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_basic_27","seed":20027}}
|
||||
1
tests/filament_group/golden/config_b/basic_47.json
Normal file
1
tests/filament_group/golden/config_b/basic_47.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":279.0},"context":{"group_info":{"filament_volume_map":[2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":3},"machine_info":{"machine_filament_info":[[{"color":"#21E724FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#B2066AFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#727804FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#CBC06DFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#0EF122FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#7299D2FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#EA9A57FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#3A2E9EFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2"],"filament_info":[{"color":"#88704DFF","is_support":false,"type":"PETG","usage_type":1},{"color":"#D3D1CCFF","is_support":false,"type":"PLA","usage_type":1},{"color":"#F8C24BFF","is_support":false,"type":"PLA","usage_type":1}],"flush_matrix":[[[0.0,123.0057144165039,149.25132751464844],[140.3647918701172,0.0,395.5540771484375],[354.4726257324219,160.0218048095703,0.0]],[[0.0,249.49559020996094,285.7671203613281],[366.1941223144531,0.0,411.5499267578125],[69.0042724609375,557.7216186523438,0.0]]],"layer_filaments":[[0,2],[0,1],[0,1],[0,2],[0,2],[0,1,2],[0,1,2],[0],[0],[0],[0],[1],[0,1],[0],[0],[0,1],[1],[0,1],[0,1],[0,1],[0,1],[1,2],[2],[1],[1],[1],[0],[0],[0],[0],[0],[1],[1],[1],[2],[1,2],[1,2],[1],[1,2],[2],[1,2],[1],[1,2],[1,2],[1,2],[2],[2],[1,2],[1],[0],[0],[0],[0,1],[0,1],[1],[0,1],[1],[1,2],[0,1],[0,1],[0,1],[0,1],[0,1,2],[1,2],[1,2],[1,2],[1,2],[2],[2],[2],[1],[1],[1],[1],[1],[1],[0,1],[0],[0],[0],[0],[0],[0],[0],[0],[0,1],[1],[1,2],[1],[0,1],[0],[0],[0],[0],[0],[0],[0,1],[0,2],[2],[0],[1,2],[0,1,2],[0,1,2],[0,1,2],[0,1,2],[0,1,2],[0,2],[1],[1],[1],[0,1],[0,1,2],[0,2],[0],[1],[0],[0],[0],[0],[0],[0,2],[0],[0],[0],[0],[0],[0],[0,1],[0],[0],[0,1],[1],[1],[1],[2],[0,2],[2],[0,2],[0],[2],[1,2],[0,1],[0,1],[0,1,2],[0,1],[0,1],[2],[2],[0,2],[1,2],[1],[1,2],[1,2],[1,2],[1,2],[1],[1],[1],[1],[1],[1],[1],[0,1],[0,1],[0,1],[0],[0],[0],[0],[0],[0],[2],[1],[1],[0],[0],[0,2],[1],[1],[1,2],[1,2],[0,1,2],[0,1,2],[0,1,2],[0],[0],[0],[0,2],[2],[0,1],[0],[1,2],[2],[1],[1,2],[1,2],[1,2],[0,1,2],[1],[1],[1],[1],[1],[0],[0,1],[1],[2],[1],[1,2],[0,1],[0,2],[0,1,2]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":3}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_basic_47","seed":20047}}
|
||||
1
tests/filament_group/golden/config_b/constraint_103.json
Normal file
1
tests/filament_group/golden/config_b/constraint_103.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":12987,"full_score":6744.9032},"context":{"group_info":{"filament_volume_map":[2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":4},"machine_info":{"machine_filament_info":[[{"color":"#1BC545FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#D494DDFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#99E903FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#6C8B32FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#961DFEFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FF2B42FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#BFEBE0FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A6F508FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3"],"filament_info":[{"color":"#2093D1FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#4B9E95FF","is_support":false,"type":"PLA","usage_type":1},{"color":"#79642EFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#DC89BAFF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,145.34756469726563,196.37205505371094,358.7149353027344],[25.324295043945313,0.0,117.23784637451172,303.9642333984375],[553.1095581054688,434.2644348144531,0.0,28.46591567993164],[561.9080810546875,554.3380737304688,435.35601806640625,0.0]],[[0.0,412.2175598144531,165.17893981933594,252.97967529296875],[259.94940185546875,0.0,117.8436279296875,560.5171508789063],[168.64022827148438,568.7840576171875,0.0,28.568143844604492],[517.0733642578125,385.4801330566406,224.5548095703125,0.0]]],"layer_filaments":[[0,3],[1,3],[0,3],[0,1,3],[0,1,3],[1,3],[0,1,3],[1,2,3],[0,2],[2],[2],[2],[3],[1,2,3],[2,3],[1,2,3],[3],[3],[3],[3],[0,3],[3],[3],[2],[3],[2],[2],[0,2,3],[0,2,3],[0,1,2],[0,2],[2],[2],[2],[2],[2],[2],[2],[1,2],[1,2],[1,2],[1,2],[1,2],[2],[2],[2],[1],[1],[3],[3],[1],[0,1],[0,1],[0,1],[0,2,3],[0,2,3],[0],[0],[0,1],[0,1],[0,1,3],[0,1,3],[0,1,3],[3],[2],[2],[2],[2,3],[3],[0],[1,2,3],[3],[3],[1],[1],[1],[1],[0],[0,3],[0,3],[3],[3],[0,3],[3],[3],[3],[3],[2,3],[2,3],[2,3],[2,3],[0,2,3],[0,2,3],[0,3],[1,2,3],[3],[1],[3],[0],[0],[2],[2],[0,1,3],[0,3],[0],[0],[0],[0,2],[0,2],[2],[2],[2],[0,2],[2,3],[2,3],[2,3],[0,2,3],[0,2,3],[0,1,2,3],[0,2,3],[0,2,3],[2,3],[2],[2],[1,2],[2],[2],[0,3],[0,1],[0,1],[3],[3],[0,1,3],[0,1,3],[0,2,3],[0,3],[0],[0,2],[2],[0],[0,1],[0,1],[0,3],[0,3],[0,3],[0,3],[0,1,2],[0,2],[2,3],[1,2,3],[0,1,2],[3],[3],[3],[3],[1],[0,1],[0,1,3],[0,1,3],[0,1,2,3],[1,2,3],[1,2,3],[0],[0],[0],[0],[1],[3],[3],[0,1,2],[1,2],[2],[0,2],[0],[0,2],[0,2],[0,2],[1,2],[1,2],[0,1,2],[2],[1,2],[1,2],[1,2],[1,3],[1],[1],[1,3],[3],[0,1,3],[0,1],[0,1],[0,1],[0],[0],[0],[0],[2],[1],[1],[1],[3],[3],[3],[0,3],[0,3],[0,3],[0,2,3],[0,2,3],[0,1,2],[0,1,2],[1,2],[0,1],[0,1,3],[0,1,2],[0,1,2,3],[0,1,2,3],[1,3],[1,2],[0,1,2],[0,1,2],[0,1,2],[0,1,2],[1],[1],[3],[3],[0,3],[0,3],[0,1,3],[0,1],[1],[0],[0,2],[0,2,3],[2,3],[1,2,3],[0,1,2,3],[0,1,2],[0,1,2],[0,1,2,3],[0,1,2,3],[0,1],[1]],"unprintable_filaments":[[],[3]],"unprintable_volumes":{"2":[3],"3":[1]}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":1},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":3}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_constraint_103","seed":20103}}
|
||||
1
tests/filament_group/golden/config_b/constraint_88.json
Normal file
1
tests/filament_group/golden/config_b/constraint_88.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":9750,"full_score":4926.6},"context":{"group_info":{"filament_volume_map":[2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":4},"machine_info":{"machine_filament_info":[[{"color":"#037005FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#D87849FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#F3CE18FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#BCFEA7FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#924B26FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#3A216BFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#D0924FFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A345ADFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3"],"filament_info":[{"color":"#7FA1F1FF","is_support":false,"type":"PLA","usage_type":1},{"color":"#5864ACFF","is_support":false,"type":"TPU","usage_type":1},{"color":"#F36945FF","is_support":false,"type":"PA","usage_type":1},{"color":"#F02F44FF","is_support":false,"type":"PLA","usage_type":1}],"flush_matrix":[[[0.0,500.582275390625,562.5870971679688,81.93852233886719],[51.72758865356445,0.0,90.24585723876953,490.09320068359375],[430.67327880859375,232.1397247314453,0.0,146.47518920898438],[161.84280395507813,211.6325225830078,363.18682861328125,0.0]],[[0.0,554.25244140625,69.40193176269531,157.41722106933594],[122.196533203125,0.0,229.16275024414063,209.3227996826172],[192.6871337890625,78.21271514892578,0.0,35.126708984375],[227.9981689453125,364.66082763671875,66.126220703125,0.0]]],"layer_filaments":[[0,1,2],[0,1,2],[0,1,2,3],[0,1,2,3],[0,3],[0,3],[0,2],[0,1,3],[3],[1],[0],[2,3],[2],[2],[0,1,3],[0,1,3],[1,2,3],[0,1,2,3],[0,1,2,3],[0,2,3],[0,1,2],[0,1,2],[0,2],[0,2],[2],[2],[2],[0,2],[0,1,2],[0,1,2],[0,1,2],[0,1,2],[0],[2],[0,2],[0,2],[2],[2,3],[1,2],[1],[0],[0],[0,1,3],[1],[1],[0,2,3],[1,2],[1],[1],[2],[2],[1,2],[1,2],[1],[1,2],[1,2],[1,3],[3],[3],[1],[1],[0,1],[0,1],[0],[0,1],[0,1],[0],[1,2,3],[0,1,3],[0,1,2],[0,1],[1,2,3],[2],[2],[2],[2],[2],[1],[2,3],[1,2],[0],[0],[0],[0,2],[0],[0],[0],[0,2],[0,1,3],[0,1,3],[0,1,3],[1,3],[1],[0],[0],[0],[0,3],[0,3],[0],[0],[0],[1],[1,2],[1,2],[2],[0,2],[0,2],[0,2],[0,2],[1],[1],[1],[1],[1,2],[1],[1],[3],[0,3],[0,3],[0,2,3],[2,3],[2,3],[2],[2,3],[2,3],[3],[3],[1],[1,2],[0,1,2],[2],[2],[3],[3],[0,1,2],[0,1,2],[0,2],[0,2],[0],[0],[0],[1,2,3],[1,2,3],[1,2,3],[0,1,2],[0,1],[0,1],[1,2],[1,2],[0,1,2],[0,1,2],[1,2,3],[1,2,3],[1,2,3]],"unprintable_filaments":[[0],[2]],"unprintable_volumes":{"1":[1],"2":[1],"3":[1]}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":1}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_constraint_88","seed":20088}}
|
||||
1
tests/filament_group/golden/config_b/constraint_97.json
Normal file
1
tests/filament_group/golden/config_b/constraint_97.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":3367,"full_score":2146.2712},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":5},"machine_info":{"machine_filament_info":[[{"color":"#2A5557FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#995701FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#CBB5F1FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#E09394FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#38D65DFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A65DE8FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#D6E92AFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#21A474FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,6],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4"],"filament_info":[{"color":"#341F11FF","is_support":false,"type":"ABS","usage_type":1},{"color":"#58D9A4FF","is_support":false,"type":"PETG","usage_type":1},{"color":"#11D7FFFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#756DEFFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#D28F74FF","is_support":false,"type":"TPU","usage_type":1}],"flush_matrix":[[[0.0,40.422149658203125,281.1308898925781,420.726318359375,245.7325439453125],[564.1063842773438,0.0,80.42797088623047,132.09776306152344,33.372379302978516],[29.10088539123535,327.1266784667969,0.0,318.0596923828125,352.4109191894531],[79.35222625732422,349.1927795410156,450.20599365234375,0.0,473.4333190917969],[84.93012237548828,343.9147033691406,480.2047119140625,440.6584167480469,0.0]],[[0.0,203.69725036621094,148.45620727539063,208.9656524658203,217.2571258544922],[170.0343780517578,0.0,516.4771728515625,587.4338989257813,442.1988830566406],[37.863525390625,265.5264892578125,0.0,318.85748291015625,227.68455505371094],[257.746826171875,217.14395141601563,120.68830108642578,0.0,310.3852233886719],[327.35687255859375,328.03076171875,271.71405029296875,420.61297607421875,0.0]]],"layer_filaments":[[1,2],[1],[1],[1],[1],[0,1],[1],[2],[1],[1,3],[4],[1],[4],[4],[4],[4],[2],[2,4],[4],[4],[2],[1,2],[1,2],[1],[0],[0],[0],[0,3],[2],[2],[2,3],[2],[2],[2],[2],[2],[2],[2],[0],[0],[2],[3],[4],[4],[2],[2],[2],[2],[2],[2],[2,3],[2,3],[2,3],[0,2,3],[1,3],[1,3,4],[1,3,4],[1,3,4],[3],[0],[1],[1],[1],[1,4],[1,4],[1,4],[0,1,4],[0,1,3,4],[0,1,3],[0,3],[0,3],[2,3,4],[2,4],[2],[2],[3],[1,3],[1,3,4],[1,2,3,4],[0,1,2,3,4],[0,1,2,4],[2,3,4],[2,3,4],[1],[4],[1,4],[1,4],[3],[3],[3],[3],[3],[1,3],[1,3,4],[1,3,4],[1,3],[0,1,3],[0,1,2,3],[0,2,3],[3],[1,3],[0,3,4],[2,3,4],[2,4],[2,3,4],[2,3,4],[0,2,3,4],[0,2,3,4],[0,1,2,3,4],[0,3,4],[0,3,4],[0],[0],[0,4],[4],[0,2],[0,2],[2],[2],[2],[0,2,3],[0,2,3],[0,1,2,3],[1,2,3],[2,3],[2,3],[0,2],[0,2,3],[2,3,4],[0,2,3],[0,1,2],[0,1,2],[0,1,2],[0,1,2],[1,2],[2],[2],[0,2],[0,2],[0,2,3],[0,2,3],[0,3],[0]],"unprintable_filaments":[[3],[]],"unprintable_volumes":{"3":[3],"4":[0]}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2,3]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":3},{"diameter":"0.4","extruder_id":1,"group_id":3,"volume_type":1}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_constraint_97","seed":20097}}
|
||||
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":3336,"full_score":2002.2096},"context":{"group_info":{"filament_volume_map":[2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":1,"total_filament_num":4},"machine_info":{"machine_filament_info":[[{"color":"#28AC58FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#412846FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#733049FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#0AC1B4FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#A402D9FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#0E94B8FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#3F2B52FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#CC874FFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3"],"filament_info":[{"color":"#2739B9FF","is_support":false,"type":"PETG","usage_type":1},{"color":"#103A81FF","is_support":false,"type":"PA","usage_type":1},{"color":"#4B971AFF","is_support":false,"type":"PETG","usage_type":1},{"color":"#82A327FF","is_support":false,"type":"PLA","usage_type":1}],"flush_matrix":[[[0.0,160.58099365234375,186.70541381835938,293.4424133300781],[452.10089111328125,0.0,427.1346435546875,482.00482177734375],[26.20694351196289,235.17530822753906,0.0,410.3768615722656],[269.29888916015625,244.5442657470703,496.617919921875,0.0]],[[0.0,409.6128845214844,39.27631378173828,447.314697265625],[520.747314453125,0.0,143.31735229492188,21.33603286743164],[532.3141479492188,215.94216918945313,0.0,394.37481689453125],[321.899169921875,174.60623168945313,109.6452407836914,0.0]]],"layer_filaments":[[1,2,3],[1],[0,1],[0,1],[0,1],[0,1,2],[2],[0],[0],[2],[2],[0,3],[0,3],[0,2,3],[0,2,3],[0,2,3],[0,1,2,3],[0,1,2],[0,2],[0,2],[0,2],[1,2],[2],[2],[2],[2],[1,2],[1,2,3],[1,2,3],[0,2,3],[2,3],[3],[3],[3],[2,3],[2,3],[1,2],[0,2],[0,2],[2],[2],[2],[0,2],[2],[2],[0,1],[0,1],[1],[1],[1],[1],[1,2],[1],[0,2],[0,2,3],[2,3],[3],[0],[0,3],[3],[3],[2,3],[2,3],[2,3],[0,1],[0,1],[1],[1,3],[0,1,3],[0,1],[0,1,2],[0,1,2],[0,3],[0],[2],[2,3],[0,2,3],[0,1],[1],[2],[0],[0,2],[0,2],[2],[0,3],[0,1],[0,1],[0],[0,3],[0,2],[0],[0,1],[1],[1],[1],[0,1],[0],[0],[0,2,3],[3],[3],[3],[0,2],[0,2],[0,1],[0],[0],[0,1],[0,1,2],[0,2],[0,2],[0,1,2],[2,3],[2,3],[2,3],[3],[1,3],[1,3],[3],[1],[0,1,3],[0,3],[0,3],[0,3],[3],[3],[1],[0,1],[0,1],[0,1,2],[0,1],[0,1],[0,1,2],[0,1,2,3],[0,2,3],[3],[3],[3],[3],[1,2,3],[1,3],[1,2,3],[1,2,3],[1,2],[1,2],[1,2],[1],[1,2],[0,1,2],[2,3],[2,3],[3],[3],[0],[0,1],[0,1],[0,1],[0,2],[0,3],[2,3],[2,3],[2,3],[2],[2],[2],[0],[0,3],[0],[0],[0]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"B","id":"B_mode_bestfit_162","seed":20162}}
|
||||
1
tests/filament_group/golden/config_b/mode_match_148.json
Normal file
1
tests/filament_group/golden/config_b/mode_match_148.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_b/mode_time_168.json
Normal file
1
tests/filament_group/golden/config_b/mode_time_168.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":5010,"full_score":2616.536},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":5},"machine_info":{"machine_filament_info":[[{"color":"#A7BDFDFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#E4B564FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#64E4F7FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#79AE21FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}],[{"color":"#BB3A10FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#342AAEFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#1B853FFF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#C98C73FF","extruder_id":1,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4,4],"prefer_non_model_filament":[false,false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4"],"filament_info":[{"color":"#B0F63DFF","is_support":false,"type":"TPU","usage_type":1},{"color":"#053F79FF","is_support":false,"type":"ABS","usage_type":1},{"color":"#2236EAFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#3E1A46FF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#E193E6FF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,357.560302734375,158.03790283203125,78.87968444824219,56.35820388793945],[312.62969970703125,0.0,578.679443359375,354.6175537109375,333.78289794921875],[385.2695007324219,297.87310791015625,0.0,18.705421447753906,101.41615295410156],[106.06452941894531,286.4847412109375,112.56126403808594,0.0,244.12152099609375],[234.8699951171875,51.119590759277344,95.25473022460938,578.6362915039063,0.0]],[[0.0,354.75567626953125,51.230716705322266,514.29296875,451.8372802734375],[30.5628719329834,0.0,426.8621520996094,304.156005859375,114.46688079833984],[305.9984436035156,567.757568359375,0.0,254.84019470214844,480.94757080078125],[302.3028259277344,503.4031982421875,186.15228271484375,0.0,498.27532958984375],[198.755859375,412.3115234375,207.9266815185547,364.662841796875,0.0]]],"layer_filaments":[[1,2,4],[1,2],[1,2],[1,2],[1],[4],[4],[4],[0,4],[0,4],[1,2],[2],[2],[0,1,4],[0,1,2],[0,1,2],[0,2],[0],[0,4],[0,3,4],[0,2,3,4],[2,4],[0,2,4],[0,1,4],[0,1,2],[0,2],[0,2,3],[0,3],[0],[0],[2],[2],[2],[0,2],[0,1],[1],[1,2],[1],[1,3],[1,3],[3],[4],[0,3,4],[0,3,4],[4],[4],[4],[4],[4],[4],[2,4],[3],[3],[0],[4],[2,4],[2],[1],[4],[4],[4],[2,3,4],[1,2,4],[2,4],[3,4],[1],[1],[2],[2,3],[2,4],[2,4],[2,4],[2,4],[2],[2],[2],[2],[2],[2],[0],[0],[0,4],[0],[0],[1],[2],[1,2,4],[1,2],[1,2],[1],[1],[1],[1],[0],[0,4],[4],[4],[4],[1],[1],[1],[0,1],[0,1],[0,1],[0,3],[3],[0,1,4],[0],[4],[2],[2],[2],[0],[2],[2],[2],[2],[2,3],[0,2,4],[4],[4],[1,4],[4]],"unprintable_filaments":[[],[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0],"1":[1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":1,"volume_type":0},{"diameter":"0.4","extruder_id":1,"group_id":2,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true,true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":true}},"metadata":{"config_type":"B","id":"B_mode_time_168","seed":20168}}
|
||||
1
tests/filament_group/golden/config_b/stress_53.json
Normal file
1
tests/filament_group/golden/config_b/stress_53.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_c/basic_3.json
Normal file
1
tests/filament_group/golden/config_c/basic_3.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":533.0},"context":{"group_info":{"filament_volume_map":[2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":3},"machine_info":{"machine_filament_info":[[{"color":"#FD981AFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#6618F5FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#BBA143FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#26550AFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[3],"prefer_non_model_filament":[false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2"],"filament_info":[{"color":"#911BD7FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#89C1C0FF","is_support":false,"type":"PA","usage_type":1},{"color":"#C64EE6FF","is_support":false,"type":"ABS","usage_type":1}],"flush_matrix":[[[0.0,64.12446594238281,186.0951385498047],[482.5750427246094,0.0,78.35060119628906],[161.81735229492188,233.08798217773438,0.0]]],"layer_filaments":[[0,1],[0,1],[0],[0],[0],[0],[0,2],[1,2],[1,2],[0],[0,2],[0,1],[0],[0,2],[0,2],[2],[2],[1],[0,2],[0,2],[0],[0,2],[2],[2],[2],[0],[0],[0,1],[0,1],[0,2],[1,2],[1,2],[0,1],[0],[0],[0],[0,2],[0,1,2],[1,2],[0],[0],[0],[0],[2],[0,2],[0,2],[1,2],[1,2],[0],[0],[2],[2],[0],[0],[2],[2],[0,2],[0,2],[2],[1,2],[1,2],[1,2],[2],[2],[1],[1],[1],[1],[1],[0,1],[0],[0],[0,2],[0,2],[0,2],[0],[0],[0,2],[1,2],[1,2],[1,2],[0,2],[1,2],[1,2],[2],[2],[2],[0,1],[0,1],[1],[1],[0],[0,2],[0,2],[0,2],[0,2],[0,2],[0,1],[0],[0],[0,1],[0,1],[1],[1,2],[1],[1],[0],[0,2],[0,2],[0,2],[0,2],[0],[1],[1],[0,1],[0,1],[1,2],[0,1],[0,1],[1],[0],[0,2],[0,2],[0],[0],[0],[0],[0,2],[2],[0],[1],[0,2],[0,2],[0,1,2],[0,2],[0,2],[0,2],[1,2],[2],[2],[1]],"unprintable_filaments":[[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0,1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":0,"group_id":1,"volume_type":1},{"diameter":"0.4","extruder_id":0,"group_id":2,"volume_type":2}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"C","id":"C_basic_3","seed":30003}}
|
||||
1
tests/filament_group/golden/config_c/basic_33.json
Normal file
1
tests/filament_group/golden/config_c/basic_33.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":0,"full_score":608.0},"context":{"group_info":{"filament_volume_map":[2,2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":5},"machine_info":{"machine_filament_info":[[{"color":"#93FE0AFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#FE6A12FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#E78D3BFF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A20CB0FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[5],"prefer_non_model_filament":[false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3","GFL_4"],"filament_info":[{"color":"#C51507FF","is_support":false,"type":"ABS","usage_type":1},{"color":"#D366B2FF","is_support":false,"type":"ABS","usage_type":1},{"color":"#D07D0EFF","is_support":false,"type":"PLA","usage_type":1},{"color":"#E4C00AFF","is_support":true,"type":"PLA-S","usage_type":0},{"color":"#12B359FF","is_support":false,"type":"PETG","usage_type":1}],"flush_matrix":[[[0.0,274.9917297363281,455.0113830566406,551.6867065429688,562.2197265625],[345.1457214355469,0.0,337.8075866699219,484.70074462890625,465.59490966796875],[332.17742919921875,481.7458801269531,0.0,339.1631164550781,394.23785400390625],[317.8833923339844,417.9119873046875,523.1845092773438,0.0,164.09495544433594],[455.5447692871094,228.3113555908203,309.9906311035156,487.07562255859375,0.0]]],"layer_filaments":[[1,3,4],[1,2],[1,2,4],[2,4],[2,4],[2,4],[3,4],[3,4],[1,3,4],[0,3,4],[0,1,3,4],[0,1,3,4],[0,1,2,3,4],[1,2],[1],[0],[4],[2],[2],[2,4],[0,2],[0,2,3],[1,2],[1],[1],[1,4],[4],[0,4],[1],[1],[1],[1,2],[0,3,4],[1,2,3],[1,2],[0,1,2],[0,1,2],[0,1,2],[2,4],[2,4],[2],[2],[1],[1],[0],[1,3,4],[0,1,3,4],[0,1,2,3],[0,1,3,4],[0,1,2],[0,2],[0,2],[2],[2],[2,3],[2,3],[0,1,4],[0,4],[0,4],[0,4],[0,2,4],[0,4],[0],[0,2],[0,2],[0,2],[0,2],[0],[0],[2],[2],[2],[0,2],[0,2],[0,2],[0],[2],[2],[2],[2],[1],[0],[0],[0],[0],[2],[2,3],[3,4],[3],[3],[0,2],[4],[0],[0],[2,3],[2,3],[2,3],[2],[1,2,4],[1,2],[1,2],[1,2,3],[2,3],[0,3],[0],[0,3],[0,2,3],[0,2],[2],[2],[2],[2],[1],[1],[1]],"unprintable_filaments":[[]],"unprintable_volumes":{}},"nozzle_info":{"extruder_nozzle_list":{"0":[0,1,2,3,4]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":0,"group_id":1,"volume_type":1},{"diameter":"0.4","extruder_id":0,"group_id":2,"volume_type":2},{"diameter":"0.4","extruder_id":0,"group_id":3,"volume_type":3},{"diameter":"0.4","extruder_id":0,"group_id":4,"volume_type":0}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"C","id":"C_basic_33","seed":30033}}
|
||||
1
tests/filament_group/golden/config_c/constraint_85.json
Normal file
1
tests/filament_group/golden/config_c/constraint_85.json
Normal file
@@ -0,0 +1 @@
|
||||
{"base_result":{"constraints_ok":true,"flush_cost":8700,"full_score":4679.32},"context":{"group_info":{"filament_volume_map":[2,2,2,2],"has_filament_switcher":false,"ignore_ext_filament":false,"max_gap_threshold":0.01,"mode":0,"strategy":0,"total_filament_num":4},"machine_info":{"machine_filament_info":[[{"color":"#D04D20FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#408006FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#A31F43FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1},{"color":"#846951FF","extruder_id":0,"is_extended":false,"is_support":false,"type":"PLA","usage_type":1}]],"master_extruder_id":0,"max_group_size":[4],"prefer_non_model_filament":[false]},"model_info":{"filament_ids":["GFL_0","GFL_1","GFL_2","GFL_3"],"filament_info":[{"color":"#92C1F9FF","is_support":false,"type":"PLA","usage_type":1},{"color":"#B0D9AAFF","is_support":false,"type":"PA","usage_type":1},{"color":"#5855D4FF","is_support":false,"type":"TPU","usage_type":1},{"color":"#2CEAEAFF","is_support":false,"type":"PLA","usage_type":1}],"flush_matrix":[[[0.0,263.98394775390625,335.4018249511719,562.2523193359375],[514.525390625,0.0,491.3005676269531,28.14336585998535],[562.559814453125,351.77215576171875,0.0,321.54388427734375],[304.2557067871094,320.45123291015625,470.2841796875,0.0]]],"layer_filaments":[[2,3],[3],[3],[3],[1,3],[1,2,3],[0,1,2],[2],[2],[2],[2],[2],[2],[1],[1,2],[0,2],[0,2],[0,2],[1],[1],[1],[1],[1],[1],[1,3],[1,3],[1,3],[0],[0],[0],[0],[0],[3],[3],[3],[1,3],[1,3],[2],[2],[0,2],[2,3],[2,3],[3],[3],[1,2],[1,3],[1,3],[1,3],[0,1,3],[1,3],[3],[3],[3],[0,3],[0,1,2],[2],[2],[3],[3],[2,3],[1,2,3],[1,2,3],[1],[1],[1,2],[1,2],[1,2],[1,2],[2],[2,3],[2,3],[3],[0,2,3],[0,2,3],[0,1,2,3],[0,1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[0,1,3],[0,1,3],[0,1,3],[0,1,2,3],[2,3],[2,3],[2],[2],[0,2],[0,2],[0,2],[0,1,2],[1,2],[2,3],[2,3],[2],[2],[0,1],[0],[1,3],[2,3],[2],[2,3],[3],[3],[3],[0,2],[0,2],[0,2],[0,2],[0,1,2],[0,1,2],[0,1,2],[0,2,3],[1,3],[1,3],[1,3],[0,1],[0,1],[1,3],[3],[2,3],[3],[3],[0,3],[0],[0],[0,3],[0,1],[0,1],[0,1],[1,3],[1,3],[3],[3],[3],[2,3],[2],[2],[1],[1],[0,1,2],[0,1,3],[2,3],[2,3],[3],[1,3],[1,3],[0,1,3],[0,2],[1,3]],"unprintable_filaments":[[]],"unprintable_volumes":{"2":[1],"3":[1]}},"nozzle_info":{"extruder_nozzle_list":{"0":[0,1,2]},"nozzle_list":[{"diameter":"0.4","extruder_id":0,"group_id":0,"volume_type":0},{"diameter":"0.4","extruder_id":0,"group_id":1,"volume_type":1},{"diameter":"0.4","extruder_id":0,"group_id":2,"volume_type":2}],"nozzle_status":{}},"speed_info":{"ams_preload_enabled":[true],"change_time_params":{"selector_load_time":1.0,"selector_unload_time":1.0,"standard_load_time":3.0,"standard_unload_time":2.0},"extruder_change_time":5.0,"filament_change_time":2.0,"filament_print_time":{},"group_with_time":false}},"metadata":{"config_type":"C","id":"C_constraint_85","seed":30085}}
|
||||
1
tests/filament_group/golden/config_c/stress_66.json
Normal file
1
tests/filament_group/golden/config_c/stress_66.json
Normal file
File diff suppressed because one or more lines are too long
1
tests/filament_group/golden/config_c/stress_79.json
Normal file
1
tests/filament_group/golden/config_c/stress_79.json
Normal file
File diff suppressed because one or more lines are too long
@@ -56,8 +56,10 @@ struct NfpPlacerFixture {
|
||||
} // namespace
|
||||
|
||||
TEST_CASE_METHOD(NfpPlacerFixture, "NfpPlacer places a single item inside the bin", "[Nesting][Placer]") {
|
||||
NfpPlacer placer = placer_with();
|
||||
// The placer only keeps references to the items it packs and re-reads them
|
||||
// from finalAlign() in its destructor, so the item must outlive the placer.
|
||||
RectangleItem item{100000000, 100000000};
|
||||
NfpPlacer placer = placer_with();
|
||||
|
||||
REQUIRE(place(placer, item));
|
||||
REQUIRE(placer.getItems().size() == 1u);
|
||||
@@ -103,12 +105,15 @@ TEST_CASE_METHOD(NfpPlacerFixture, "NfpPlacer packs many items without overlap",
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(NfpPlacerFixture, "NfpPlacer evaluates the rotation candidates", "[Nesting][Placer]") {
|
||||
// The placer re-reads its packed items from finalAlign() in its destructor,
|
||||
// so the items must outlive the placer — declare them first.
|
||||
std::vector<RectangleItem> rects = {
|
||||
{180000000, 40000000}, {180000000, 40000000}, {180000000, 40000000}};
|
||||
|
||||
Cfg cfg;
|
||||
cfg.rotations = {0.0, Pi / 2.0}; // exercise the rotation search loop
|
||||
NfpPlacer placer = placer_with(cfg);
|
||||
|
||||
std::vector<RectangleItem> rects = {
|
||||
{180000000, 40000000}, {180000000, 40000000}, {180000000, 40000000}};
|
||||
place_all(placer, rects);
|
||||
require_disjoint_in_bin(rects);
|
||||
}
|
||||
|
||||
@@ -12,15 +12,20 @@ add_executable(${_TEST_NAME}_tests
|
||||
test_clipper_offset.cpp
|
||||
test_clipper_utils.cpp
|
||||
test_config.cpp
|
||||
test_config_variant_expansion.cpp
|
||||
test_toolordering_nozzle_group.cpp
|
||||
test_preset_bundle_loading.cpp
|
||||
test_preset_setting_id.cpp
|
||||
test_preset_diff.cpp
|
||||
test_vendor_cache.cpp
|
||||
test_elephant_foot_compensation.cpp
|
||||
test_geometry.cpp
|
||||
test_multimaterial_segmentation.cpp
|
||||
test_placeholder_parser.cpp
|
||||
test_polygon.cpp
|
||||
test_mutable_polygon.cpp
|
||||
test_mutable_priority_queue.cpp
|
||||
test_nozzle_volume_type.cpp
|
||||
test_stl.cpp
|
||||
test_meshboolean.cpp
|
||||
test_marchingsquares.cpp
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Format/3mf.hpp"
|
||||
#include "libslic3r/Format/bbs_3mf.hpp"
|
||||
#include "libslic3r/Format/STL.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/Semver.hpp"
|
||||
#include "libslic3r/Preset.hpp"
|
||||
#include "libslic3r/MultiNozzleUtils.hpp"
|
||||
#include "libslic3r/ProjectTask.hpp"
|
||||
|
||||
#include <boost/filesystem/operations.hpp>
|
||||
|
||||
@@ -133,6 +139,376 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") {
|
||||
}
|
||||
}
|
||||
|
||||
// .3mf multi-nozzle round-trip.
|
||||
// Locks the load/save handling for the H2C multi-nozzle plate metadata:
|
||||
// * filament_volume_maps -> plate config "filament_volume_map" (with the >1 -> 0 clamp)
|
||||
// * nozzle_volume_type -> PlateData::nozzle_volume_types (previously write-only)
|
||||
// and pins the deliberately-lossy keys (enable_filament_dynamic_map) so a future change has to
|
||||
// consciously unpin them. Uses a store_bbs_3mf -> load_bbs_3mf cycle (no external fixture needed).
|
||||
SCENARIO("H2C multi-nozzle .3mf round-trip", "[3mf][MultiNozzle]") {
|
||||
GIVEN("a plate carrying multi-nozzle filament assignment metadata") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
// store_bbs_3mf stages Metadata/project_settings.config through the model's backup path;
|
||||
// point it at a writable temp dir (the default lives under a read-only root in CI).
|
||||
std::string backup_dir =
|
||||
(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_mn_%%%%%%%%")).string();
|
||||
boost::filesystem::create_directories(backup_dir);
|
||||
model.set_backup_path(backup_dir);
|
||||
|
||||
// Global (printer) config: give nozzle_volume_type a non-default value so the slice_info
|
||||
// read-back is a meaningful assertion (High Flow == 1).
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("nozzle_volume_type",
|
||||
new ConfigOptionEnumsGeneric({ (int) NozzleVolumeType::nvtHighFlow }));
|
||||
|
||||
PlateData* plate = new PlateData();
|
||||
plate->plate_index = 0;
|
||||
plate->is_sliced_valid = true; // gate for the slice_info.config writer (nozzle_volume_type)
|
||||
plate->filament_maps = { 1, 2, 1 }; // slice_info uses this; keep it == model_settings' value
|
||||
plate->config.set_key_value("filament_map_mode", new ConfigOptionEnum<FilamentMapMode>(fmmManual));
|
||||
plate->config.set_key_value("filament_map", new ConfigOptionInts({ 1, 2, 1 }));
|
||||
// Deliberately include out-of-range volume-type ids (2 == Hybrid, 3 == TPU High Flow):
|
||||
// the loader must clamp them back to Standard (0).
|
||||
plate->config.set_key_value("filament_volume_map", new ConfigOptionInts({ 0, 2, 1, 3 }));
|
||||
// Known-lossy: a true value must NOT survive the round-trip (slice_info hardcodes false,
|
||||
// model_settings never writes it).
|
||||
plate->config.set_key_value("enable_filament_dynamic_map", new ConfigOptionBool(true));
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
std::string test_file = std::string(TEST_DATA_DIR) + "/test_3mf/mn_roundtrip.3mf";
|
||||
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.plate_data_list.push_back(plate);
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
// LoadConfig is required for slice_info.config (nozzle_volume_type) to be parsed —
|
||||
// matches how the app loads projects.
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
boost::filesystem::remove(test_file);
|
||||
|
||||
THEN("every multi-nozzle key round-trips as expected") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_plates.size() >= 1);
|
||||
PlateData* rt = dst_plates.front();
|
||||
|
||||
// filament_map (model_settings + slice_info; already round-tripped)
|
||||
auto* fmap = rt->config.option<ConfigOptionInts>("filament_map");
|
||||
REQUIRE(fmap != nullptr);
|
||||
REQUIRE(fmap->values == std::vector<int>({ 1, 2, 1 }));
|
||||
|
||||
// filament_volume_map (model_settings) with the >1 -> 0 clamp
|
||||
auto* fvmap = rt->config.option<ConfigOptionInts>("filament_volume_map");
|
||||
REQUIRE(fvmap != nullptr);
|
||||
REQUIRE(fvmap->values == std::vector<int>({ 0, 0, 1, 0 }));
|
||||
|
||||
// nozzle_volume_type read-back into PlateData::nozzle_volume_types
|
||||
REQUIRE(rt->nozzle_volume_types == "1");
|
||||
|
||||
// enable_filament_dynamic_map pinned lossy: model_settings never serializes it and
|
||||
// slice_info hardcodes false, so the `true` we set is dropped. Pinned here
|
||||
// (absent or false, never true) so a future change that persists it must update this.
|
||||
auto* dyn = rt->config.option<ConfigOptionBool>("enable_filament_dynamic_map");
|
||||
const bool persisted_true = (dyn != nullptr && dyn->value);
|
||||
REQUIRE_FALSE(persisted_true);
|
||||
}
|
||||
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
delete plate; // store_bbs_3mf does not take ownership of the source plate
|
||||
boost::filesystem::remove_all(backup_dir);
|
||||
}
|
||||
}
|
||||
|
||||
// Saved nozzle diameter for a single-nozzle-per-extruder printer with a non-standard nozzle.
|
||||
// The grouping result rounds every nozzle diameter to the nearest of {0.2,0.4,0.6,0.8} for its
|
||||
// internal matching key. That rounded value must NOT reach the saved <filament>/<nozzle> metadata on
|
||||
// a printer whose extruders each carry one nozzle: the exact per-extruder config diameter is written
|
||||
// instead, so a 0.5 mm nozzle is preserved rather than saved as 0.4. (Only an extruder that carries a
|
||||
// nozzle cluster, which the per-extruder config cannot express, keeps the grouping result's diameter.)
|
||||
SCENARIO("Non-standard nozzle diameter survives .3mf save on a single-nozzle printer", "[3mf][MultiNozzle]") {
|
||||
GIVEN("a single-extruder plate whose nozzle is 0.5 mm and whose stamped diameter was rounded to 0.4") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
std::string backup_dir =
|
||||
(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_nd_%%%%%%%%")).string();
|
||||
boost::filesystem::create_directories(backup_dir);
|
||||
model.set_backup_path(backup_dir);
|
||||
|
||||
// Single extruder with a non-standard 0.5 mm nozzle; extruder_max_nozzle_count stays at its
|
||||
// default (no nozzle cluster), so the writer must emit the exact config diameter.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("nozzle_diameter", new ConfigOptionFloats({ 0.5 }));
|
||||
|
||||
PlateData* plate = new PlateData();
|
||||
plate->plate_index = 0;
|
||||
plate->is_sliced_valid = true; // gate for the slice_info.config writer
|
||||
plate->filament_maps = { 1 };
|
||||
|
||||
// Seed the stamped diameter with the grouping result's rounded value (0.5 -> 0.4) so the
|
||||
// assertion proves the writer ignores it and emits the exact config diameter instead.
|
||||
FilamentInfo fi;
|
||||
fi.id = 0;
|
||||
fi.type = "PLA";
|
||||
fi.color = "#FFFFFFFF";
|
||||
fi.group_id = { 0 };
|
||||
fi.nozzle_diameter = 0.4; // rounded; must NOT be the value written
|
||||
plate->slice_filaments_info.push_back(fi);
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
std::string test_file = std::string(TEST_DATA_DIR) + "/test_3mf/nd_roundtrip.3mf";
|
||||
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.plate_data_list.push_back(plate);
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
boost::filesystem::remove(test_file);
|
||||
|
||||
THEN("the saved nozzle diameter is the exact 0.5, not the rounded 0.4") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_plates.size() >= 1);
|
||||
PlateData* rt = dst_plates.front();
|
||||
|
||||
// <nozzle> tag: device-facing per-nozzle diameter string, written verbatim.
|
||||
REQUIRE(rt->nozzles_info.size() >= 1);
|
||||
REQUIRE(rt->nozzles_info.front().diameter == "0.5");
|
||||
|
||||
// <filament> tag: per-filament nozzle_diameter parsed back as 0.5, not 0.4.
|
||||
REQUIRE(rt->slice_filaments_info.size() >= 1);
|
||||
REQUIRE_THAT(rt->slice_filaments_info.front().nozzle_diameter, Catch::Matchers::WithinAbs(0.5, 1e-6));
|
||||
}
|
||||
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
delete plate; // store_bbs_3mf does not take ownership of the source plate
|
||||
boost::filesystem::remove_all(backup_dir);
|
||||
}
|
||||
}
|
||||
|
||||
// A legacy / foreign project (no multi-nozzle metadata) must load crash-safe through the BBS
|
||||
// importer and must not fabricate a filament_volume_map.
|
||||
SCENARIO("Legacy project loads crash-safe via load_bbs_3mf", "[3mf][MultiNozzle]") {
|
||||
GIVEN("a project without any multi-nozzle metadata") {
|
||||
std::string path = std::string(TEST_DATA_DIR) + "/test_3mf/Geräte/Büchse.3mf";
|
||||
Model model;
|
||||
DynamicPrintConfig config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
|
||||
WHEN("loaded through the BBS importer") {
|
||||
bool loaded = false;
|
||||
REQUIRE_NOTHROW(loaded = load_bbs_3mf(path.c_str(), &config, &ctxt, &model, &plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf,
|
||||
&file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig));
|
||||
THEN("it does not crash and invents no per-filament volume map") {
|
||||
for (PlateData* p : plates) {
|
||||
REQUIRE(p->config.option<ConfigOptionInts>("filament_volume_map") == nullptr);
|
||||
}
|
||||
}
|
||||
release_PlateData_list(plates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Device-side nozzle-grouping serialization surface.
|
||||
// Direct unit coverage for the pure serialize/deserialize + StaticNozzleGroupResult helpers that the
|
||||
// gcode.3mf writer/reader lean on.
|
||||
SCENARIO("MultiNozzle serialization helpers", "[3mf][MultiNozzle]") {
|
||||
using namespace Slic3r::MultiNozzleUtils;
|
||||
|
||||
GIVEN("NozzleInfo / NozzleGroupInfo") {
|
||||
NozzleInfo n0; n0.group_id = 0; n0.extruder_id = 0; n0.diameter = "0.4"; n0.volume_type = nvtStandard;
|
||||
NozzleInfo n1; n1.group_id = 1; n1.extruder_id = 1; n1.diameter = "0.4"; n1.volume_type = nvtHighFlow;
|
||||
|
||||
THEN("NozzleInfo::serialize matches the <nozzle> tag attributes (extruder_id 1-based)") {
|
||||
REQUIRE(n0.serialize() == "id=\"0\" extruder_id=\"1\" nozzle_diameter=\"0.4\" volume_type=\"Standard\"");
|
||||
REQUIRE(n1.serialize() == "id=\"1\" extruder_id=\"2\" nozzle_diameter=\"0.4\" volume_type=\"High Flow\"");
|
||||
}
|
||||
THEN("NozzleGroupInfo serialize/deserialize round-trips and rejects malformed input") {
|
||||
NozzleGroupInfo g("0.4", nvtHighFlow, 1, 3);
|
||||
REQUIRE(g.serialize() == "1-0.4-High Flow-3");
|
||||
auto rt = NozzleGroupInfo::deserialize(g.serialize());
|
||||
REQUIRE(rt.has_value());
|
||||
REQUIRE(*rt == g);
|
||||
REQUIRE_FALSE(NozzleGroupInfo::deserialize("1-0.4-Standard").has_value()); // too few tokens
|
||||
REQUIRE_FALSE(NozzleGroupInfo::deserialize("x-0.4-Standard-3").has_value()); // non-numeric extruder
|
||||
}
|
||||
}
|
||||
|
||||
GIVEN("a StaticNozzleGroupResult built from filament + nozzle infos") {
|
||||
std::vector<NozzleInfo> nozzles;
|
||||
{ NozzleInfo n; n.group_id = 0; n.extruder_id = 0; n.diameter = "0.4"; n.volume_type = nvtStandard; nozzles.push_back(n); }
|
||||
{ NozzleInfo n; n.group_id = 1; n.extruder_id = 1; n.diameter = "0.4"; n.volume_type = nvtHighFlow; nozzles.push_back(n); }
|
||||
|
||||
std::vector<FilamentInfo> filaments(3);
|
||||
filaments[0].id = 0; filaments[0].group_id = { 0 };
|
||||
filaments[1].id = 1; filaments[1].group_id = { 1 };
|
||||
filaments[2].id = 2; filaments[2].group_id = { 0, 1 };
|
||||
|
||||
auto result = StaticNozzleGroupResult::create(filaments, nozzles, { 0, 1, 2 }, { 0, 1, 0 }, false);
|
||||
REQUIRE(result.has_value());
|
||||
|
||||
THEN("filament->nozzle queries resolve to the stored mapping") {
|
||||
REQUIRE(result->get_extruder_count() == 2);
|
||||
REQUIRE(result->get_used_extruders() == std::vector<int>({ 0, 1 }));
|
||||
REQUIRE(result->get_used_filaments() == std::vector<unsigned int>({ 0, 1, 2 }));
|
||||
REQUIRE(result->get_nozzles_for_filament(0).size() == 1);
|
||||
REQUIRE(result->get_nozzles_for_filament(2).size() == 2);
|
||||
// first-use resolves through the (filament,nozzle) change sequences.
|
||||
auto first = result->get_first_nozzle_for_filament(1);
|
||||
REQUIRE(first.has_value());
|
||||
REQUIRE(first->group_id == 1);
|
||||
}
|
||||
THEN("empty inputs yield nullopt") {
|
||||
REQUIRE_FALSE(StaticNozzleGroupResult::create({}, nozzles, {}, {}, false).has_value());
|
||||
REQUIRE_FALSE(StaticNozzleGroupResult::create(filaments, {}, {}, {}, false).has_value());
|
||||
}
|
||||
}
|
||||
|
||||
GIVEN("load_nozzle_infos_with_compatibility fallbacks") {
|
||||
std::vector<NozzleInfo> new_format;
|
||||
{ NozzleInfo n; n.group_id = 1; n.extruder_id = 1; n.diameter = "0.4"; n.volume_type = nvtHighFlow; new_format.push_back(n); }
|
||||
{ NozzleInfo n; n.group_id = 0; n.extruder_id = 0; n.diameter = "0.4"; n.volume_type = nvtStandard; new_format.push_back(n); }
|
||||
|
||||
THEN("new-format <nozzle> tags are returned sorted by logical id") {
|
||||
auto out = load_nozzle_infos_with_compatibility(new_format, {}, {}, {}, {});
|
||||
REQUIRE(out.size() == 2);
|
||||
REQUIRE(out[0].group_id == 0);
|
||||
REQUIRE(out[1].group_id == 1);
|
||||
}
|
||||
THEN("oldest single-nozzle 3mf (no tags, no filament group_id) rebuilds from diameters/volume types") {
|
||||
std::vector<NozzleVolumeType> vt = { nvtStandard, nvtHighFlow };
|
||||
std::vector<double> dia = { 0.4, 0.4 };
|
||||
auto out = load_nozzle_infos_with_compatibility({}, {}, {}, vt, dia);
|
||||
REQUIRE(out.size() == 2);
|
||||
REQUIRE(out[0].extruder_id == 0);
|
||||
REQUIRE(out[0].volume_type == nvtStandard);
|
||||
REQUIRE(out[1].volume_type == nvtHighFlow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The layer-aware grouping result must survive the gcode.3mf write/read as
|
||||
// <nozzle> tags and the enable_filament_dynamic_map flag. Proves the parse_filament_info stamping,
|
||||
// the NOZZLE_TAG writer, the _handle_config_nozzle reader, and the nozzles_info plate copy.
|
||||
SCENARIO("Nozzle-group metadata .3mf round-trip", "[3mf][MultiNozzle]") {
|
||||
GIVEN("a plate carrying a two-nozzle LayeredNozzleGroupResult") {
|
||||
Model model;
|
||||
std::string src_file = std::string(TEST_DATA_DIR) + "/test_3mf/Prusa.stl";
|
||||
REQUIRE(load_stl(src_file.c_str(), &model));
|
||||
model.add_default_instances();
|
||||
|
||||
std::string backup_dir =
|
||||
(boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_ng_%%%%%%%%")).string();
|
||||
boost::filesystem::create_directories(backup_dir);
|
||||
model.set_backup_path(backup_dir);
|
||||
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
|
||||
std::vector<MultiNozzleUtils::NozzleInfo> nozzles;
|
||||
{ MultiNozzleUtils::NozzleInfo n; n.group_id = 0; n.extruder_id = 0; n.diameter = "0.4"; n.volume_type = NozzleVolumeType::nvtStandard; nozzles.push_back(n); }
|
||||
{ MultiNozzleUtils::NozzleInfo n; n.group_id = 1; n.extruder_id = 1; n.diameter = "0.4"; n.volume_type = NozzleVolumeType::nvtHighFlow; nozzles.push_back(n); }
|
||||
auto group = MultiNozzleUtils::LayeredNozzleGroupResult::create(
|
||||
std::vector<int>{ 0, 1, 0 }, nozzles, std::vector<unsigned int>{ 0, 1, 2 });
|
||||
REQUIRE(group.has_value());
|
||||
|
||||
PlateData* plate = new PlateData();
|
||||
plate->plate_index = 0;
|
||||
plate->is_sliced_valid = true;
|
||||
plate->filament_maps = { 1, 2, 1 };
|
||||
plate->nozzle_group_result = group;
|
||||
plate->config.set_key_value("filament_map_mode", new ConfigOptionEnum<FilamentMapMode>(fmmManual));
|
||||
plate->config.set_key_value("filament_map", new ConfigOptionInts({ 1, 2, 1 }));
|
||||
|
||||
WHEN("stored to and reloaded from a .3mf") {
|
||||
std::string test_file = std::string(TEST_DATA_DIR) + "/test_3mf/ng_roundtrip.3mf";
|
||||
|
||||
StoreParams store_params;
|
||||
store_params.path = test_file.c_str();
|
||||
store_params.model = &model;
|
||||
store_params.config = &config;
|
||||
store_params.plate_data_list.push_back(plate);
|
||||
store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence;
|
||||
REQUIRE(store_bbs_3mf(store_params));
|
||||
|
||||
Model dst_model;
|
||||
DynamicPrintConfig dst_config;
|
||||
ConfigSubstitutionContext ctxt{ ForwardCompatibilitySubstitutionRule::Enable };
|
||||
PlateDataPtrs dst_plates;
|
||||
std::vector<Preset*> project_presets;
|
||||
bool is_bbl_3mf = false, is_orca_3mf = false;
|
||||
Semver file_version;
|
||||
bool loaded = load_bbs_3mf(test_file.c_str(), &dst_config, &ctxt, &dst_model, &dst_plates,
|
||||
&project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr,
|
||||
LoadStrategy::LoadModel | LoadStrategy::LoadConfig);
|
||||
boost::filesystem::remove(test_file);
|
||||
|
||||
THEN("the <nozzle> tags round-trip into the loaded plate's nozzles_info") {
|
||||
REQUIRE(loaded);
|
||||
REQUIRE(dst_plates.size() >= 1);
|
||||
PlateData* rt = dst_plates.front();
|
||||
|
||||
REQUIRE(rt->nozzles_info.size() == 2);
|
||||
// reader stores extruder_id 0-based (tag is 1-based), diameter/volume_type preserved.
|
||||
std::sort(rt->nozzles_info.begin(), rt->nozzles_info.end());
|
||||
REQUIRE(rt->nozzles_info[0].group_id == 0);
|
||||
REQUIRE(rt->nozzles_info[0].extruder_id == 0);
|
||||
REQUIRE(rt->nozzles_info[0].diameter == "0.4");
|
||||
REQUIRE(rt->nozzles_info[0].volume_type == NozzleVolumeType::nvtStandard);
|
||||
REQUIRE(rt->nozzles_info[1].group_id == 1);
|
||||
REQUIRE(rt->nozzles_info[1].extruder_id == 1);
|
||||
REQUIRE(rt->nozzles_info[1].volume_type == NozzleVolumeType::nvtHighFlow);
|
||||
|
||||
// A static (non-selector) result must persist enable_filament_dynamic_map = false.
|
||||
auto* dyn = rt->config.option<ConfigOptionBool>("enable_filament_dynamic_map");
|
||||
const bool persisted_true = (dyn != nullptr && dyn->value);
|
||||
REQUIRE_FALSE(persisted_true);
|
||||
}
|
||||
|
||||
release_PlateData_list(dst_plates);
|
||||
}
|
||||
delete plate;
|
||||
boost::filesystem::remove_all(backup_dir);
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("2D convex hull of sinking object", "[3mf][.]") {
|
||||
GIVEN("model") {
|
||||
// load a model
|
||||
|
||||
@@ -59,7 +59,9 @@ TEST_CASE("NetworkLibraryVersionInfo::from_static", "[BambuNetworking]") {
|
||||
REQUIRE(info.suffix == "");
|
||||
REQUIRE(info.display_name == "02.03.00.62");
|
||||
REQUIRE(info.url_override == "");
|
||||
REQUIRE(info.is_latest == true);
|
||||
// from_static no longer propagates the static is_latest flag; it is a placeholder
|
||||
// that get_all_available_versions() assigns once the list is sorted newest-first.
|
||||
REQUIRE(info.is_latest == false);
|
||||
REQUIRE(info.warning == "");
|
||||
REQUIRE(info.is_discovered == false);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include "libslic3r/calib.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
@@ -38,3 +42,69 @@ TEST_CASE("Zero calibration line width resolves to a positive default", "[Calib]
|
||||
REQUIRE(pattern.line_width() > 0.);
|
||||
REQUIRE(pattern.line_width_first_layer() > 0.);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct EndState { double final_e; double max_e; };
|
||||
|
||||
EndState simulate_absolute_e(const std::string &gcode)
|
||||
{
|
||||
double final_e = 0.;
|
||||
double max_e = 0.;
|
||||
|
||||
std::istringstream lines(gcode);
|
||||
std::string line;
|
||||
while (std::getline(lines, line)) {
|
||||
std::istringstream words(line);
|
||||
std::string op;
|
||||
if (!(words >> op))
|
||||
continue;
|
||||
if (op != "G1" && op != "G0" && op != "G92")
|
||||
continue;
|
||||
|
||||
std::string word;
|
||||
while (words >> word) {
|
||||
if (word.size() >= 2 && word[0] == 'E') {
|
||||
final_e = std::stod(word.substr(1));
|
||||
max_e = std::max(max_e, final_e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {final_e, max_e};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("PA pattern resets the extruder after the final layer in absolute E mode", "[Calib][Regression]")
|
||||
{
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.set_deserialize_strict({
|
||||
{"use_relative_e_distances", "0"},
|
||||
{"line_width", "0.45"},
|
||||
{"initial_layer_line_width", "0.45"},
|
||||
});
|
||||
|
||||
Model model;
|
||||
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
|
||||
|
||||
Calib_Params params;
|
||||
params.mode = CalibMode::Calib_PA_Pattern;
|
||||
params.start = 0.;
|
||||
params.end = 0.08;
|
||||
params.step = 0.002;
|
||||
|
||||
CalibPressureAdvancePattern pattern(params, config, /* is_bbl_machine */ false, *model.objects.front(), Vec3d(0, 0, 0));
|
||||
const CustomGCode::Info info = pattern.generate_custom_gcodes(config, /* is_bbl_machine */ false, *model.objects.front(),
|
||||
Vec3d(0, 0, 0));
|
||||
|
||||
std::string gcode;
|
||||
for (const CustomGCode::Item &item : info.gcodes)
|
||||
gcode += item.extra;
|
||||
|
||||
const EndState state = simulate_absolute_e(gcode);
|
||||
|
||||
REQUIRE(state.max_e > 1.);
|
||||
REQUIRE_THAT(state.final_e, Catch::Matchers::WithinAbs(0., 1e-9));
|
||||
}
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
#include "libslic3r/LocalesUtils.hpp"
|
||||
|
||||
#include <cereal/types/polymorphic.hpp>
|
||||
#include <cereal/types/string.hpp>
|
||||
#include <cereal/types/vector.hpp>
|
||||
#include <cereal/types/string.hpp>
|
||||
#include <cereal/types/vector.hpp>
|
||||
#include <cereal/archives/binary.hpp>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
SCENARIO("Generic config validation performs as expected.", "[Config]") {
|
||||
@@ -401,3 +405,377 @@ SCENARIO("update_diff_values_to_child_config tolerates legacy machine-limit vect
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
TEST_CASE("save_to_json round-trips plugin capability references as strings", "[Config][plugins]") {
|
||||
namespace fs = boost::filesystem;
|
||||
const fs::path tmp = fs::temp_directory_path() / fs::unique_path("orca_plugins_%%%%-%%%%.json");
|
||||
const std::vector<std::string> refs = {
|
||||
"local_plugin;;inset",
|
||||
"cloud_plugin;550e8400-e29b-41d4-a716-446655440000;inset"
|
||||
};
|
||||
|
||||
std::unique_ptr<DynamicPrintConfig> config_ptr(
|
||||
DynamicPrintConfig::new_from_defaults_keys({"slicing_pipeline_plugin"}));
|
||||
DynamicPrintConfig config = std::move(*config_ptr);
|
||||
config.option<ConfigOptionStrings>("slicing_pipeline_plugin", true)->values = refs;
|
||||
config.save_to_json(tmp.string(), "test_preset", "User", "1.0.0.0");
|
||||
|
||||
nlohmann::json j;
|
||||
{
|
||||
boost::nowide::ifstream ifs(tmp.string());
|
||||
ifs >> j;
|
||||
}
|
||||
REQUIRE(j["slicing_pipeline_plugin"] == nlohmann::json(refs));
|
||||
CHECK_FALSE(j.contains("plugins"));
|
||||
|
||||
DynamicPrintConfig reloaded = DynamicPrintConfig::full_print_config();
|
||||
ConfigSubstitutionContext substitutions(ForwardCompatibilitySubstitutionRule::Disable);
|
||||
std::map<std::string, std::string> key_values;
|
||||
std::string reason;
|
||||
REQUIRE(reloaded.load_from_json(tmp.string(), substitutions, true, key_values, reason) == 0);
|
||||
CHECK(reason.empty());
|
||||
CHECK(reloaded.option<ConfigOptionStrings>("slicing_pipeline_plugin")->values == refs);
|
||||
|
||||
fs::remove(tmp);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin capability references survive string-map serialization", "[Config][plugins]") {
|
||||
const std::vector<std::string> refs = {
|
||||
"master_plugin;;header-stamp",
|
||||
"Sample Plugin;1f998ea9-0183-4cc5-957f-4eef659ba4e6;G-code Benchmark (.py)"
|
||||
};
|
||||
|
||||
DynamicPrintConfig original = DynamicPrintConfig::full_print_config();
|
||||
original.option<ConfigOptionStrings>("slicing_pipeline_plugin", true)->values = refs;
|
||||
|
||||
std::map<std::string, std::string> serialized{
|
||||
{"slicing_pipeline_plugin", original.option<ConfigOptionStrings>("slicing_pipeline_plugin")->serialize()}
|
||||
};
|
||||
CHECK(serialized["slicing_pipeline_plugin"].find("\"master_plugin;;header-stamp\"") != std::string::npos);
|
||||
|
||||
DynamicPrintConfig reloaded = DynamicPrintConfig::full_print_config();
|
||||
reloaded.load_string_map(serialized, ForwardCompatibilitySubstitutionRule::Disable);
|
||||
|
||||
CHECK(reloaded.option<ConfigOptionStrings>("slicing_pipeline_plugin")->values == refs);
|
||||
}
|
||||
|
||||
TEST_CASE("parse_capability_ref parses local and cloud references", "[Config][plugin]") {
|
||||
const auto local = Slic3r::parse_capability_ref("local_plugin;;post_process");
|
||||
REQUIRE(local.has_value());
|
||||
CHECK(local->name == "local_plugin");
|
||||
CHECK(local->capability_name == "post_process");
|
||||
CHECK(local->uuid.empty());
|
||||
|
||||
const auto cloud = Slic3r::parse_capability_ref(
|
||||
"cloud_plugin;550e8400-e29b-41d4-a716-446655440000;post_process");
|
||||
REQUIRE(cloud.has_value());
|
||||
CHECK(cloud->name == "cloud_plugin");
|
||||
CHECK(cloud->capability_name == "post_process");
|
||||
CHECK(cloud->uuid == "550e8400-e29b-41d4-a716-446655440000");
|
||||
}
|
||||
|
||||
TEST_CASE("parse_capability_ref rejects malformed input", "[Config][plugin]") {
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref("").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref("plugin").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref("plugin;uuid").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref(";;capability").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref(";uuid;capability").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref("plugin;;").has_value());
|
||||
CHECK_FALSE(Slic3r::parse_capability_ref("plugin;uuid;").has_value());
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Installs a stub capability resolver that echoes the capability type into the reference, so tests
|
||||
// can assert each plugin-backed option resolved with its own ConfigOptionDef::plugin_type. Resets
|
||||
// the global resolver on teardown -- tests run in random order and other cases assert the
|
||||
// no-resolver behavior (an absent "plugins" manifest).
|
||||
struct PluginResolverFixture {
|
||||
PluginResolverFixture() {
|
||||
ConfigBase::set_resolve_capability_fn([](const std::string& name, const std::string& type) {
|
||||
return name.empty() ? std::string() : name + ";;" + type;
|
||||
});
|
||||
}
|
||||
~PluginResolverFixture() { ConfigBase::set_resolve_capability_fn(nullptr); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE_METHOD(PluginResolverFixture,
|
||||
"update_plugin_manifest derives references generically from plugin-backed options",
|
||||
"[Config][plugins]") {
|
||||
// Both scalar (printer_agent) and vector (slicing_pipeline_plugin) options opt in via a non-empty
|
||||
// ConfigOptionDef::plugin_type (is_plugin_backed) and are resolved with it -- there is no hardcoded
|
||||
// per-option switch. printer_agent in particular relies on its plugin_type metadata being wired up
|
||||
// (it is edited via a dedicated widget, not the plugin_picker).
|
||||
std::unique_ptr<DynamicPrintConfig> config_ptr(DynamicPrintConfig::new_from_defaults_keys(
|
||||
{"slicing_pipeline_plugin", "printer_agent"}));
|
||||
DynamicPrintConfig config = std::move(*config_ptr);
|
||||
config.option<ConfigOptionStrings>("slicing_pipeline_plugin", true)->values = {"sp"};
|
||||
config.option<ConfigOptionString>("printer_agent", true)->value = "agent";
|
||||
|
||||
config.update_plugin_manifest();
|
||||
const std::vector<std::string> manifest = config.option<ConfigOptionStrings>("plugins")->values;
|
||||
|
||||
using Catch::Matchers::VectorContains;
|
||||
REQUIRE_THAT(manifest, VectorContains(std::string("sp;;slicing-pipeline")));
|
||||
REQUIRE_THAT(manifest, VectorContains(std::string("agent;;printer-connection")));
|
||||
CHECK(manifest.size() == 2);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(PluginResolverFixture,
|
||||
"update_plugin_manifest de-duplicates references and skips unset options",
|
||||
"[Config][plugins]") {
|
||||
std::unique_ptr<DynamicPrintConfig> config_ptr(DynamicPrintConfig::new_from_defaults_keys(
|
||||
{"slicing_pipeline_plugin", "printer_agent"}));
|
||||
DynamicPrintConfig config = std::move(*config_ptr);
|
||||
config.option<ConfigOptionStrings>("slicing_pipeline_plugin", true)->values = {"x", "x"}; // duplicate
|
||||
// printer_agent stays at its default empty value -> contributes nothing to the manifest.
|
||||
|
||||
config.update_plugin_manifest();
|
||||
const std::vector<std::string> manifest = config.option<ConfigOptionStrings>("plugins")->values;
|
||||
|
||||
CHECK(manifest == std::vector<std::string>{"x;;slicing-pipeline"});
|
||||
}
|
||||
|
||||
TEST_CASE("H2C/A2L-era multi-nozzle and pre-heat config keys exist", "[config]") {
|
||||
// Foundation keys backing H2C 6-nozzle cluster grouping, the pre-heat/pre-cool time
|
||||
// model, and wipe-tower nozzle-change handling. Defaults must keep existing
|
||||
// single-nozzle printers behaving identically.
|
||||
Slic3r::DynamicPrintConfig config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
|
||||
// Printer / per-extruder options
|
||||
REQUIRE(config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count")->values == std::vector<int>{1});
|
||||
REQUIRE(config.option<ConfigOptionBool>("enable_pre_heating") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionBool>("enable_pre_heating")->value == false);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("hotend_cooling_rate") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("hotend_heating_rate") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloat>("machine_hotend_change_time") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloat>("machine_prepare_compensation_time") != nullptr);
|
||||
|
||||
// Filament pre-cooling / ramming / nozzle-change (nc) options
|
||||
REQUIRE(config.option<ConfigOptionIntsNullable>("filament_pre_cooling_temperature") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionIntsNullable>("filament_pre_cooling_temperature_nc") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_preheat_temperature_delta") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_retract_length_nc") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_change_length_nc") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_prime_volume_nc") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_ramming_travel_time") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_ramming_travel_time_nc") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed") != nullptr);
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed_nc") != nullptr);
|
||||
|
||||
// Spot-check defaults that must not alter existing behavior.
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_retract_length_nc")->values == std::vector<double>{10.});
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_prime_volume_nc")->values == std::vector<double>{60.});
|
||||
REQUIRE(config.option<ConfigOptionIntsNullable>("filament_pre_cooling_temperature_nc")->values == std::vector<int>{0});
|
||||
REQUIRE(config.option<ConfigOptionFloatsNullable>("filament_ramming_volumetric_speed")->values == std::vector<double>{-1});
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index with stride=1 copies values correctly", "[Config][set_to_index]") {
|
||||
GIVEN("A destination vector and a source vector with 3 values") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionFloats src({10.0, 20.0, 30.0});
|
||||
std::vector<int> variant_index = {0, 1, 2};
|
||||
int stride = 1;
|
||||
|
||||
WHEN("set_to_index is called with stride=1") {
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("The destination contains the source values") {
|
||||
REQUIRE(dest.values.size() == 3);
|
||||
REQUIRE(dest.values[0] == 10.0);
|
||||
REQUIRE(dest.values[1] == 20.0);
|
||||
REQUIRE(dest.values[2] == 30.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GIVEN("A destination vector and a source vector with subset mapping") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionFloats src({100.0, 200.0, 300.0});
|
||||
std::vector<int> variant_index = {1, 2};
|
||||
int stride = 1;
|
||||
|
||||
WHEN("set_to_index maps only indices 1 and 2") {
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("Only the mapped values are copied, default fills the others") {
|
||||
REQUIRE(dest.values.size() == 2);
|
||||
REQUIRE(dest.values[0] == 200.0);
|
||||
REQUIRE(dest.values[1] == 300.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index with stride=2 copies grouped values correctly", "[Config][set_to_index]") {
|
||||
GIVEN("A destination vector and a source vector with stride=2 (e.g., nozzle groups)") {
|
||||
// Source has 4 groups of 2 values each: (10,11), (20,21), (30,31), (40,41)
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionFloats src({10.0, 11.0, 20.0, 21.0, 30.0, 31.0, 40.0, 41.0});
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index maps groups 0, 1, 3") {
|
||||
std::vector<int> variant_index = {0, 1, 3};
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("The destination has 3 groups (6 values) mapped correctly") {
|
||||
REQUIRE(dest.values.size() == 6);
|
||||
// Group 0: (10, 11)
|
||||
REQUIRE(dest.values[0] == 10.0);
|
||||
REQUIRE(dest.values[1] == 11.0);
|
||||
// Group 1: (20, 21)
|
||||
REQUIRE(dest.values[2] == 20.0);
|
||||
REQUIRE(dest.values[3] == 21.0);
|
||||
// Group 3: (40, 41)
|
||||
REQUIRE(dest.values[4] == 40.0);
|
||||
REQUIRE(dest.values[5] == 41.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GIVEN("A destination and a single-group source") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
// Source has 1 group of 2 values
|
||||
Slic3r::ConfigOptionFloats src({50.0, 60.0});
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index maps group 0 from a single-group source") {
|
||||
std::vector<int> variant_index = {0};
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("The destination contains the single group correctly") {
|
||||
REQUIRE(dest.values.size() == 2);
|
||||
REQUIRE(dest.values[0] == 50.0);
|
||||
REQUIRE(dest.values[1] == 60.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index handles empty dest_index", "[Config][set_to_index]") {
|
||||
GIVEN("A destination and source with stride=2") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionFloats src({10.0, 11.0, 20.0, 21.0});
|
||||
std::vector<int> variant_index = {};
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index is called with an empty index vector") {
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("The destination is resized to 0") {
|
||||
REQUIRE(dest.values.size() == 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index handles nil values in source", "[Config][set_to_index]") {
|
||||
GIVEN("A source with a nil group (stride=2)") {
|
||||
Slic3r::ConfigOptionFloatsNullable dest({0.0});
|
||||
Slic3r::ConfigOptionFloatsNullable src({10.0, 11.0,
|
||||
Slic3r::ConfigOptionFloatsNullable::nil_value(), Slic3r::ConfigOptionFloatsNullable::nil_value(),
|
||||
30.0, 31.0});
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index maps all groups including the nil one") {
|
||||
std::vector<int> variant_index = {0, 1, 2};
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("Non-nil groups are copied and the nil group keeps the default") {
|
||||
REQUIRE(dest.values.size() == 6);
|
||||
// Group 0: (10, 11) — copied
|
||||
REQUIRE(dest.values[0] == 10.0);
|
||||
REQUIRE(dest.values[1] == 11.0);
|
||||
// Group 1: nil — keeps default (the front value = 10.0)
|
||||
REQUIRE(dest.values[2] == 10.0);
|
||||
REQUIRE(dest.values[3] == 10.0);
|
||||
// Group 2: (30, 31) — copied
|
||||
REQUIRE(dest.values[4] == 30.0);
|
||||
REQUIRE(dest.values[5] == 31.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index handles out-of-bounds dest_index", "[Config][set_to_index]") {
|
||||
GIVEN("A source with only 2 groups (4 values) but dest_index references group 3") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionFloats src({10.0, 11.0, 20.0, 21.0}); // 2 groups of stride 2
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index maps group 3 which is out of bounds") {
|
||||
std::vector<int> variant_index = {0, 3}; // group 3 is out of range
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("Group 0 is copied, group 3 falls back to default without crashing") {
|
||||
REQUIRE(dest.values.size() == 4);
|
||||
// Group 0: (10, 11) — copied
|
||||
REQUIRE(dest.values[0] == 10.0);
|
||||
REQUIRE(dest.values[1] == 11.0);
|
||||
// Group 3: out of bounds — keeps default (10.0 = src.values.front())
|
||||
REQUIRE(dest.values[2] == 10.0);
|
||||
REQUIRE(dest.values[3] == 10.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index handles negative dest_index values", "[Config][set_to_index]") {
|
||||
GIVEN("A destination and source with a negative entry in dest_index") {
|
||||
// The dest is initially empty, so resize fills all slots with src.values.front().
|
||||
Slic3r::ConfigOptionFloats dest;
|
||||
Slic3r::ConfigOptionFloats src({100.0, 101.0, 200.0, 201.0});
|
||||
int stride = 2;
|
||||
|
||||
WHEN("set_to_index maps group 0 and a negative index") {
|
||||
std::vector<int> variant_index = {-1, 0};
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("The negative index is skipped, the valid group is copied") {
|
||||
REQUIRE(dest.values.size() == 4);
|
||||
// Position 0 (variant_index[0] = -1): skipped, keeps default fill
|
||||
// from resize (src.values.front() = 100.0, applied to all new elements)
|
||||
REQUIRE(dest.values[0] == 100.0);
|
||||
REQUIRE(dest.values[1] == 100.0);
|
||||
// Position 1 (variant_index[1] = 0): copied from group 0 of src
|
||||
REQUIRE(dest.values[2] == 100.0);
|
||||
REQUIRE(dest.values[3] == 101.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index handles single-element groups with stride=1", "[Config][set_to_index]") {
|
||||
GIVEN("A destination re-mapping one variant index with a stride=1 source") {
|
||||
// Simulates the PrintObject.cpp code path: stride=1, variant_index={1}
|
||||
Slic3r::ConfigOptionFloats dest({99.0, 99.0, 99.0, 99.0}); // pre-sized for 4 extruders
|
||||
Slic3r::ConfigOptionFloats src({0.5, 0.6, 0.7, 0.8}); // 4 extruder values
|
||||
std::vector<int> variant_index = {1}; // only extruder 1 is active
|
||||
int stride = 1;
|
||||
|
||||
WHEN("set_to_index is called") {
|
||||
dest.set_to_index(&src, variant_index, stride);
|
||||
|
||||
THEN("Only the mapped value is copied, rest are defaulted") {
|
||||
REQUIRE(dest.values.size() == 1);
|
||||
REQUIRE(dest.values[0] == 0.6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SCENARIO("ConfigOptionVector::set_to_index throws on incompatible type", "[Config][set_to_index]") {
|
||||
GIVEN("A Floats destination and an Ints source") {
|
||||
Slic3r::ConfigOptionFloats dest({0.0});
|
||||
Slic3r::ConfigOptionInts src({1, 2, 3});
|
||||
std::vector<int> variant_index = {0};
|
||||
int stride = 1;
|
||||
|
||||
WHEN("set_to_index is called with mismatched types") {
|
||||
THEN("A ConfigurationError is thrown") {
|
||||
REQUIRE_THROWS_AS(dest.set_to_index(&src, variant_index, stride), Slic3r::ConfigurationError);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
336
tests/libslic3r/test_config_variant_expansion.cpp
Normal file
336
tests/libslic3r/test_config_variant_expansion.cpp
Normal file
@@ -0,0 +1,336 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
namespace {
|
||||
|
||||
// A 2-extruder printer whose second extruder holds both a Standard and a High Flow nozzle
|
||||
// (nozzle_volume_type Hybrid), described by extruder_nozzle_stats. The variant lists carry one
|
||||
// column per (extruder x volume type) as composed from the presets.
|
||||
DynamicPrintConfig make_hybrid_printer_config()
|
||||
{
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#3|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
return config;
|
||||
}
|
||||
|
||||
void add_print_variant_columns(DynamicPrintConfig &config)
|
||||
{
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("outer_wall_speed", true)->values = {30., 200., 50., 500.};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("apply_override fills nil entries from the 0-based default index", "[Config]")
|
||||
{
|
||||
ConfigOptionFloats machine({10., 20., 30.});
|
||||
ConfigOptionFloatsNullable filament;
|
||||
filament.values = {ConfigOptionFloatsNullable::nil_value(), 42.};
|
||||
|
||||
SECTION("a nil entry picks the slot addressed by its 0-based index") {
|
||||
std::vector<int> slot_index{2, 0};
|
||||
ConfigOptionFloats resolved(machine);
|
||||
REQUIRE(resolved.apply_override(&filament, slot_index));
|
||||
REQUIRE(resolved.values == std::vector<double>({30., 42.}));
|
||||
}
|
||||
|
||||
SECTION("an index past the machine slots falls back to the first slot") {
|
||||
std::vector<int> slot_index{5, 0};
|
||||
ConfigOptionFloats resolved(machine);
|
||||
REQUIRE(resolved.apply_override(&filament, slot_index));
|
||||
REQUIRE(resolved.values == std::vector<double>({10., 42.}));
|
||||
}
|
||||
|
||||
SECTION("a negative index (unresolved slot) falls back to the first slot") {
|
||||
std::vector<int> slot_index{-1, 0};
|
||||
ConfigOptionFloats resolved(machine);
|
||||
REQUIRE(resolved.apply_override(&filament, slot_index));
|
||||
REQUIRE(resolved.values == std::vector<double>({10., 42.}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("get_config_index_base resolves (volume type, extruder type, id) to a slot", "[Config]")
|
||||
{
|
||||
const std::vector<std::string> variant_list = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
const std::vector<int> variant_ids = {1, 1, 2, 2};
|
||||
|
||||
SECTION("a matching (variant, id) pair yields its slot") {
|
||||
REQUIRE(get_config_index_base(nvtStandard, etDirectDrive, 1, variant_list, variant_ids) == 0);
|
||||
REQUIRE(get_config_index_base(nvtHighFlow, etDirectDrive, 1, variant_list, variant_ids) == 1);
|
||||
REQUIRE(get_config_index_base(nvtStandard, etDirectDrive, 2, variant_list, variant_ids) == 2);
|
||||
REQUIRE(get_config_index_base(nvtHighFlow, etDirectDrive, 2, variant_list, variant_ids) == 3);
|
||||
}
|
||||
|
||||
SECTION("no matching column falls back to slot 0") {
|
||||
REQUIRE(get_config_index_base(nvtStandard, etDirectDrive, 3, variant_list, variant_ids) == 0);
|
||||
REQUIRE(get_config_index_base(nvtStandard, etBowden, 1, variant_list, variant_ids) == 0);
|
||||
}
|
||||
|
||||
SECTION("Hybrid is not a preset variant string and falls back to slot 0") {
|
||||
REQUIRE(get_config_index_base(nvtHybrid, etDirectDrive, 2, variant_list, variant_ids) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("get_extruder_nozzle_volume_count reads the per-extruder volume-type layout", "[Config]")
|
||||
{
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
|
||||
SECTION("absent stats fall back to one slot per extruder") {
|
||||
DynamicPrintConfig config;
|
||||
REQUIRE(config.get_extruder_nozzle_volume_count(2, nozzle_volume_types) == 2);
|
||||
REQUIRE(nozzle_volume_types.size() == 2);
|
||||
REQUIRE(nozzle_volume_types[0].empty());
|
||||
REQUIRE(nozzle_volume_types[1].empty());
|
||||
}
|
||||
|
||||
SECTION("stats sized differently from the extruder count are ignored") {
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1"};
|
||||
REQUIRE(config.get_extruder_nozzle_volume_count(2, nozzle_volume_types) == 2);
|
||||
REQUIRE(nozzle_volume_types[0].empty());
|
||||
REQUIRE(nozzle_volume_types[1].empty());
|
||||
}
|
||||
|
||||
SECTION("single volume type per extruder counts one slot each") {
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "High Flow#1"};
|
||||
REQUIRE(config.get_extruder_nozzle_volume_count(2, nozzle_volume_types) == 2);
|
||||
REQUIRE(nozzle_volume_types[0] == std::vector<NozzleVolumeType>{nvtStandard});
|
||||
REQUIRE(nozzle_volume_types[1] == std::vector<NozzleVolumeType>{nvtHighFlow});
|
||||
}
|
||||
|
||||
SECTION("a mixed-nozzle extruder contributes one slot per volume type, ascending enum order") {
|
||||
DynamicPrintConfig config;
|
||||
// list High Flow first in the token string: parsing must still order Standard before High Flow
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#3", "High Flow#3|Standard#3"};
|
||||
REQUIRE(config.get_extruder_nozzle_volume_count(2, nozzle_volume_types) == 3);
|
||||
REQUIRE(nozzle_volume_types[0] == std::vector<NozzleVolumeType>{nvtStandard});
|
||||
REQUIRE(nozzle_volume_types[1] == std::vector<NozzleVolumeType>({nvtStandard, nvtHighFlow}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("update_values_to_printer_extruders expands one slot per (extruder x volume type)", "[Config]")
|
||||
{
|
||||
SECTION("Hybrid extruder yields three slots, extruder-ascending then volume-ascending") {
|
||||
DynamicPrintConfig config = make_hybrid_printer_config();
|
||||
add_print_variant_columns(config);
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
REQUIRE(count == 3);
|
||||
|
||||
std::vector<int> variant_index = config.update_values_to_printer_extruders(config, extruder_count, count, nozzle_volume_types,
|
||||
print_options_with_variant, "print_extruder_id", "print_extruder_variant");
|
||||
|
||||
REQUIRE(variant_index == std::vector<int>({0, 2, 3}));
|
||||
REQUIRE(config.option<ConfigOptionFloats>("outer_wall_speed")->values == std::vector<double>({30., 50., 500.}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("print_extruder_id")->values == std::vector<int>({1, 2, 2}));
|
||||
REQUIRE(config.option<ConfigOptionStrings>("print_extruder_variant")->values ==
|
||||
std::vector<std::string>({"Direct Drive Standard", "Direct Drive Standard", "Direct Drive High Flow"}));
|
||||
}
|
||||
|
||||
SECTION("stride-2 options keep (normal, silent) pairs together per slot") {
|
||||
DynamicPrintConfig config = make_hybrid_printer_config();
|
||||
config.option<ConfigOptionInts>("printer_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("printer_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("machine_max_speed_x", true)->values = {100., 50., 110., 55., 120., 60., 130., 65.};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
std::vector<int> variant_index = config.update_values_to_printer_extruders(config, extruder_count, count, nozzle_volume_types,
|
||||
printer_options_with_variant_2, "printer_extruder_id", "printer_extruder_variant", 2);
|
||||
|
||||
REQUIRE(variant_index == std::vector<int>({0, 2, 3}));
|
||||
REQUIRE(config.option<ConfigOptionFloats>("machine_max_speed_x")->values ==
|
||||
std::vector<double>({100., 50., 120., 60., 130., 65.}));
|
||||
}
|
||||
|
||||
SECTION("single-slot expansion on a Hybrid extruder resolves via the filament volume type") {
|
||||
DynamicPrintConfig printer_config = make_hybrid_printer_config();
|
||||
|
||||
DynamicPrintConfig filament_config;
|
||||
filament_config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
filament_config.option<ConfigOptionFloats>("filament_max_volumetric_speed", true)->values = {12., 20.};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = printer_config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
SECTION("default filament volume type selects the Standard column") {
|
||||
std::vector<int> variant_index = filament_config.update_values_to_printer_extruders(printer_config, extruder_count, count,
|
||||
nozzle_volume_types, filament_options_with_variant, "", "filament_extruder_variant", 1, 2);
|
||||
REQUIRE(variant_index == std::vector<int>({0}));
|
||||
REQUIRE(filament_config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12.}));
|
||||
}
|
||||
|
||||
SECTION("a High Flow filament volume type selects the High Flow column") {
|
||||
std::vector<int> variant_index = filament_config.update_values_to_printer_extruders(printer_config, extruder_count, count,
|
||||
nozzle_volume_types, filament_options_with_variant, "", "filament_extruder_variant", 1, 2, nvtHighFlow);
|
||||
REQUIRE(variant_index == std::vector<int>({1}));
|
||||
REQUIRE(filament_config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({20.}));
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("an extruder without per-type stats does not overrun the slot table when another is Hybrid") {
|
||||
DynamicPrintConfig config;
|
||||
// e0 carries no per-type stats (empty entry), so the summed volume-type count (2) does
|
||||
// not exceed the extruder count even though the Hybrid e1 emits one slot per volume type.
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"", "Standard#3|High Flow#3"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
add_print_variant_columns(config);
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
REQUIRE(count == 2);
|
||||
REQUIRE(nozzle_volume_types[0].empty());
|
||||
|
||||
std::vector<int> variant_index = config.update_values_to_printer_extruders(config, extruder_count, count, nozzle_volume_types,
|
||||
print_options_with_variant, "print_extruder_id", "print_extruder_variant");
|
||||
|
||||
// e0 resolves by its configured type; the Hybrid e1 emits one slot per stats volume type
|
||||
REQUIRE(variant_index == std::vector<int>({0, 2, 3}));
|
||||
REQUIRE(config.option<ConfigOptionFloats>("outer_wall_speed")->values == std::vector<double>({30., 50., 500.}));
|
||||
}
|
||||
|
||||
SECTION("without Hybrid or extra slots the expansion matches the per-extruder resolution") {
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHighFlow};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
add_print_variant_columns(config);
|
||||
|
||||
// compute what the per-extruder loop resolves directly, before the arrays are rewritten
|
||||
std::vector<int> expected_index;
|
||||
for (int e_index = 0; e_index < 2; e_index++)
|
||||
expected_index.push_back(config.get_index_for_extruder(e_index + 1, "print_extruder_id", etDirectDrive,
|
||||
e_index == 0 ? nvtStandard : nvtHighFlow, "print_extruder_variant"));
|
||||
REQUIRE(expected_index == std::vector<int>({0, 3}));
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
REQUIRE(count == 2);
|
||||
|
||||
std::vector<int> variant_index = config.update_values_to_printer_extruders(config, extruder_count, count, nozzle_volume_types,
|
||||
print_options_with_variant, "print_extruder_id", "print_extruder_variant");
|
||||
|
||||
REQUIRE(variant_index == expected_index);
|
||||
REQUIRE(config.option<ConfigOptionFloats>("outer_wall_speed")->values == std::vector<double>({30., 500.}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("update_values_to_printer_extruders_for_multiple_filaments resolves per-filament slots", "[Config]")
|
||||
{
|
||||
auto make_filament_arrays = [](DynamicPrintConfig &config) {
|
||||
config.option<ConfigOptionInts>("filament_self_index", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("filament_max_volumetric_speed", true)->values = {12., 20., 13., 21.};
|
||||
};
|
||||
|
||||
std::set<std::string> filament_keys = filament_options_with_variant;
|
||||
filament_keys.insert("filament_self_index");
|
||||
|
||||
SECTION("filament_volume_map picks the concrete volume type on a Hybrid extruder") {
|
||||
DynamicPrintConfig config = make_hybrid_printer_config();
|
||||
make_filament_arrays(config);
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {nvtStandard, nvtHighFlow};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
|
||||
REQUIRE(config.option<ConfigOptionStrings>("filament_extruder_variant")->values ==
|
||||
std::vector<std::string>({"Direct Drive Standard", "Direct Drive High Flow"}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
|
||||
}
|
||||
|
||||
SECTION("a volume map not sized to the filament count is ignored") {
|
||||
DynamicPrintConfig config = make_hybrid_printer_config();
|
||||
make_filament_arrays(config);
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {2, 2};
|
||||
// the registered default is a single-element vector; it must not override slot resolution
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {nvtStandard};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
|
||||
// Hybrid resolves as Standard when no usable per-filament map exists
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 13.}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
|
||||
}
|
||||
|
||||
SECTION("a single-filament explicit assignment on a Hybrid extruder is honored") {
|
||||
DynamicPrintConfig config = make_hybrid_printer_config();
|
||||
config.option<ConfigOptionInts>("filament_self_index", true)->values = {1, 1};
|
||||
config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("filament_max_volumetric_speed", true)->values = {12., 20.};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {2};
|
||||
// sized to the (single) filament count: the producers guarantee sizing, so a
|
||||
// single-filament map is as trustworthy as any other and the explicit High Flow
|
||||
// request must win over the Hybrid->Standard fallback
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {nvtHighFlow};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
|
||||
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({20.}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1}));
|
||||
}
|
||||
|
||||
SECTION("without Hybrid or extra slots the volume map is not consulted") {
|
||||
DynamicPrintConfig config;
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHighFlow};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
make_filament_arrays(config);
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2};
|
||||
// sized to the filament count, but inert because no extruder exposes multiple volume types
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {nvtHighFlow, nvtStandard};
|
||||
|
||||
std::vector<std::vector<NozzleVolumeType>> nozzle_volume_types;
|
||||
int extruder_count = 2;
|
||||
int count = config.get_extruder_nozzle_volume_count(extruder_count, nozzle_volume_types);
|
||||
REQUIRE(count == 2);
|
||||
|
||||
config.update_values_to_printer_extruders_for_multiple_filaments(config, extruder_count, count, filament_keys,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
|
||||
// filament 1 keeps its extruder's Standard column, filament 2 its extruder's High Flow column
|
||||
REQUIRE(config.option<ConfigOptionFloats>("filament_max_volumetric_speed")->values == std::vector<double>({12., 21.}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>({1, 2}));
|
||||
}
|
||||
}
|
||||
57
tests/libslic3r/test_multimaterial_segmentation.cpp
Normal file
57
tests/libslic3r/test_multimaterial_segmentation.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
// MultiMaterialSegmentation.hpp declares boost::polygon traits for ColoredLine, so its
|
||||
// geometry/boost dependencies must be included first.
|
||||
#include <boost/polygon/polygon.hpp>
|
||||
#include "libslic3r/Line.hpp"
|
||||
#include "libslic3r/Flow.hpp"
|
||||
#include "libslic3r/MultiMaterialSegmentation.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("Multi-material segmentation resolves the outer-wall line width", "[MultiMaterialSegmentation][Regression]")
|
||||
{
|
||||
struct Case
|
||||
{
|
||||
std::string description;
|
||||
double outer_value;
|
||||
bool outer_percent;
|
||||
double line_value;
|
||||
bool line_percent;
|
||||
std::vector<double> nozzle_diameters;
|
||||
int outer_wall_filament_id;
|
||||
double expected;
|
||||
};
|
||||
|
||||
auto c = GENERATE(values<Case>({
|
||||
{"absolute outer-wall width is used as-is", 0.6, false, 0.42, false, {0.4}, 1, 0.6},
|
||||
{"percent outer-wall width uses the nozzle", 120, true, 0.42, false, {0.5}, 1, 0.6},
|
||||
{"zero outer-wall width uses the line width", 0, false, 0.5, false, {0.4}, 1, 0.5},
|
||||
{"zero outer-wall width uses a percent line", 0, false, 100, true, {0.5}, 1, 0.5},
|
||||
{"zero width falls back to auto", 0, false, 0, false, {0.4}, 1, Flow::auto_extrusion_width(frExternalPerimeter, 0.4)},
|
||||
{"the auto fallback scales with the nozzle", 0, false, 0, false, {0.6}, 1, Flow::auto_extrusion_width(frExternalPerimeter, 0.6)},
|
||||
{"a percent width uses the outer wall's nozzle", 120, true, 0.42, false, {0.4, 0.8}, 2, 0.96},
|
||||
{"the auto width uses the outer wall's nozzle", 0, false, 0, false, {0.4, 0.8}, 2, Flow::auto_extrusion_width(frExternalPerimeter, 0.8)},
|
||||
{"an absolute width ignores the nozzle", 0.6, false, 0.42, false, {0.4, 0.8}, 2, 0.6},
|
||||
{"a zero percent width uses the line width", 0, true, 0.5, false, {0.4}, 1, 0.5},
|
||||
{"an unset filament id uses the first nozzle", 0, false, 0, false, {0.4, 0.8}, 0, Flow::auto_extrusion_width(frExternalPerimeter, 0.4)},
|
||||
{"an out-of-range filament id uses nozzle 1", 0, false, 0, false, {0.4, 0.8}, 5, Flow::auto_extrusion_width(frExternalPerimeter, 0.4)},
|
||||
}));
|
||||
|
||||
DYNAMIC_SECTION(c.description)
|
||||
{
|
||||
PrintConfig print_config;
|
||||
print_config.nozzle_diameter.values = c.nozzle_diameters;
|
||||
|
||||
PrintObjectConfig object_config;
|
||||
object_config.line_width = ConfigOptionFloatOrPercent(c.line_value, c.line_percent);
|
||||
|
||||
PrintRegionConfig region_config;
|
||||
region_config.outer_wall_line_width = ConfigOptionFloatOrPercent(c.outer_value, c.outer_percent);
|
||||
region_config.outer_wall_filament_id.value = c.outer_wall_filament_id;
|
||||
|
||||
REQUIRE_THAT(resolve_outer_wall_line_width(region_config, object_config, print_config),
|
||||
Catch::Matchers::WithinAbs(c.expected, 1e-9));
|
||||
}
|
||||
}
|
||||
31
tests/libslic3r/test_nozzle_volume_type.cpp
Normal file
31
tests/libslic3r/test_nozzle_volume_type.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("convert_to_nvt_type maps extruder variant strings to nozzle volume types", "[Config]")
|
||||
{
|
||||
SECTION("Direct Drive variants") {
|
||||
REQUIRE(convert_to_nvt_type("Direct Drive Standard") == nvtStandard);
|
||||
REQUIRE(convert_to_nvt_type("Direct Drive High Flow") == nvtHighFlow);
|
||||
REQUIRE(convert_to_nvt_type("Direct Drive TPU High Flow") == nvtTPUHighFlow);
|
||||
}
|
||||
|
||||
SECTION("Bowden variants") {
|
||||
REQUIRE(convert_to_nvt_type("Bowden Standard") == nvtStandard);
|
||||
REQUIRE(convert_to_nvt_type("Bowden High Flow") == nvtHighFlow);
|
||||
}
|
||||
|
||||
SECTION("Unparsable strings fall back to hybrid") {
|
||||
REQUIRE(convert_to_nvt_type("Unknown Extruder") == nvtHybrid);
|
||||
REQUIRE(convert_to_nvt_type("") == nvtHybrid);
|
||||
REQUIRE(convert_to_nvt_type("High Flow") == nvtHybrid);
|
||||
REQUIRE(convert_to_nvt_type("Direct Drive") == nvtHybrid);
|
||||
}
|
||||
|
||||
SECTION("Whitespace around the volume-type remainder is trimmed") {
|
||||
REQUIRE(convert_to_nvt_type("Direct Drive High Flow ") == nvtHighFlow);
|
||||
REQUIRE(convert_to_nvt_type(" Bowden Standard") == nvtStandard);
|
||||
}
|
||||
}
|
||||
35
tests/libslic3r/test_preset_diff.cpp
Normal file
35
tests/libslic3r/test_preset_diff.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/Preset.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
// Regression test for the python-plugin branch's intentional divergence from
|
||||
// upstream in add_correct_opts_to_diff() (src/libslic3r/Preset.cpp): a vector
|
||||
// option entry whose index is beyond the reference vector's length is reported
|
||||
// dirty even when it duplicates an existing value. On main these duplicates
|
||||
// were NOT flagged. See the comment on add_correct_opts_to_diff() in src/libslic3r/Preset.cpp.
|
||||
TEST_CASE("deep_diff flags new vector entries that duplicate values[0]", "[PresetDiff][Config]")
|
||||
{
|
||||
// reference: single-extruder vector (one entry)
|
||||
Preset reference(Preset::TYPE_PRINTER, "ref");
|
||||
reference.config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4});
|
||||
|
||||
// edited: a second extruder entry was added whose value duplicates the first
|
||||
Preset edited(Preset::TYPE_PRINTER, "edited");
|
||||
edited.config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4});
|
||||
|
||||
// deep_compare = true routes through deep_diff() -> add_correct_opts_to_diff()
|
||||
std::vector<std::string> diff =
|
||||
PresetCollection::dirty_options(&edited, &reference, /*deep_compare=*/true);
|
||||
|
||||
// The new index #1 is reported dirty even though 0.4 == values[0] (0.4).
|
||||
REQUIRE(std::find(diff.begin(), diff.end(), "nozzle_diameter#1") != diff.end());
|
||||
|
||||
// Sanity: the unchanged existing index #0 is NOT reported, so the rule is
|
||||
// specific to new indices rather than flagging the whole vector.
|
||||
REQUIRE(std::find(diff.begin(), diff.end(), "nozzle_diameter#0") == diff.end());
|
||||
}
|
||||
936
tests/libslic3r/test_toolordering_nozzle_group.cpp
Normal file
936
tests/libslic3r/test_toolordering_nozzle_group.cpp
Normal file
@@ -0,0 +1,936 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include "libslic3r/FilamentGroupUtils.hpp"
|
||||
#include "libslic3r/MultiNozzleUtils.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include "libslic3r/GCode/ToolOrdering.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/Print.hpp"
|
||||
#include "libslic3r/TriangleMesh.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
// H2C/A2L multi-nozzle filament grouping core.
|
||||
//
|
||||
// These tests pin the behaviour of the grouping result type
|
||||
// (Slic3r::MultiNozzleUtils::LayeredNozzleGroupResult) that GCode consumes via
|
||||
// group_result->get_nozzle_id(filament, layer) and
|
||||
// group_result->get_first_nozzle_for_filament(filament)->group_id.
|
||||
//
|
||||
// The central requirement is ZERO behaviour change for existing (single-nozzle)
|
||||
// printers: with extruder_max_nozzle_count == 1 per extruder the result collapses
|
||||
// to the classic filament->extruder grouping (nozzle id == extruder id).
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::MultiNozzleUtils;
|
||||
|
||||
namespace {
|
||||
// Build a trivial "one logical nozzle per extruder" list, the single-nozzle case
|
||||
// that every current printer profile produces.
|
||||
std::vector<NozzleInfo> single_nozzle_per_extruder(int extruder_count)
|
||||
{
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
for (int e = 0; e < extruder_count; ++e) {
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard;
|
||||
n.extruder_id = e;
|
||||
n.group_id = e; // one nozzle per extruder => nozzle id == extruder id
|
||||
nozzle_list.push_back(n);
|
||||
}
|
||||
return nozzle_list;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Multi-nozzle gate predicate mirrors BambuStudio", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// The multi-nozzle gate: std::any_of(extruder_max_nozzle_count > 1).
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
|
||||
auto *opt = config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count");
|
||||
REQUIRE(opt != nullptr); // extruder_max_nozzle_count must be a real config option
|
||||
|
||||
// extruder_nozzle_stats must be a real config option so printer profiles and
|
||||
// 3mf projects round-trip the per-extruder nozzle inventory (GUI producers wire it later).
|
||||
REQUIRE(config.option<ConfigOptionStrings>("extruder_nozzle_stats") != nullptr);
|
||||
|
||||
auto has_multiple_nozzle = [](const std::vector<int> &values) {
|
||||
return std::any_of(values.begin(), values.end(), [](int v) { return v > 1; });
|
||||
};
|
||||
|
||||
// Default for every existing printer: 1 nozzle per extruder => gate is closed.
|
||||
REQUIRE_FALSE(has_multiple_nozzle(opt->values));
|
||||
|
||||
// Synthetic H2C-like machine: extruder 1 is a 6-nozzle cluster => gate opens.
|
||||
REQUIRE(has_multiple_nozzle(std::vector<int>{1, 6}));
|
||||
}
|
||||
|
||||
TEST_CASE("Single-nozzle grouping: every filament maps to its extruder nozzle", "[ToolOrdering][H2C]")
|
||||
{
|
||||
SECTION("single extruder => all filaments map to nozzle 0")
|
||||
{
|
||||
auto nozzle_list = single_nozzle_per_extruder(1);
|
||||
// 3 filaments, all assigned to the single extruder 0.
|
||||
std::vector<int> filament_nozzle_map = {0, 0, 0};
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2};
|
||||
|
||||
auto group_opt = LayeredNozzleGroupResult::create(filament_nozzle_map, nozzle_list, used_filaments);
|
||||
REQUIRE(group_opt.has_value());
|
||||
auto &group = *group_opt;
|
||||
|
||||
for (int f = 0; f < 3; ++f) {
|
||||
REQUIRE(group.get_nozzle_id(f) == 0);
|
||||
REQUIRE(group.get_extruder_id(f) == 0);
|
||||
auto first = group.get_first_nozzle_for_filament(f);
|
||||
REQUIRE(first.has_value());
|
||||
REQUIRE(first->group_id == 0);
|
||||
}
|
||||
REQUIRE_FALSE(group.is_support_dynamic_nozzle_map());
|
||||
}
|
||||
|
||||
SECTION("dual extruder => nozzle id equals the classic extruder grouping")
|
||||
{
|
||||
auto nozzle_list = single_nozzle_per_extruder(2);
|
||||
// filament -> extruder map (the map Orca's reorder already computes).
|
||||
std::vector<int> filament_map = {0, 1, 0, 1};
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2, 3};
|
||||
|
||||
auto group_opt = LayeredNozzleGroupResult::create(filament_map, nozzle_list, used_filaments);
|
||||
REQUIRE(group_opt.has_value());
|
||||
auto &group = *group_opt;
|
||||
|
||||
REQUIRE(group.get_nozzle_id(0) == 0);
|
||||
REQUIRE(group.get_nozzle_id(1) == 1);
|
||||
REQUIRE(group.get_nozzle_id(2) == 0);
|
||||
REQUIRE(group.get_nozzle_id(3) == 1);
|
||||
// With one nozzle per extruder, nozzle id and extruder id agree.
|
||||
for (int f = 0; f < 4; ++f)
|
||||
REQUIRE(group.get_nozzle_id(f) == group.get_extruder_id(f));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("H2C multi-nozzle: filaments get distinct nozzles on the 6-nozzle extruder", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// Synthetic H2C-like config: 2 extruders, extruder_max_nozzle_count = {1, 6},
|
||||
// 4 filaments all assigned to extruder 1 (0-based). Each filament requests a
|
||||
// distinct logical nozzle cluster (as the grouping algorithm would emit), so the
|
||||
// create() overload must resolve them to 4 distinct physical nozzles.
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2, 3};
|
||||
std::vector<int> filament_map = {1, 1, 1, 1}; // extruder 1
|
||||
std::vector<int> filament_volume_map = {0, 0, 0, 0}; // nvtStandard
|
||||
std::vector<int> filament_nozzle_map = {0, 1, 2, 3}; // distinct clusters
|
||||
|
||||
std::vector<std::map<NozzleVolumeType, int>> nozzle_count(2);
|
||||
nozzle_count[0] = {}; // extruder 0: 1-nozzle (unused here)
|
||||
nozzle_count[1] = {{nvtStandard, 6}}; // extruder 1: 6-nozzle cluster
|
||||
|
||||
auto group_opt = LayeredNozzleGroupResult::create(
|
||||
used_filaments, filament_map, filament_volume_map, filament_nozzle_map, nozzle_count, 0.4f);
|
||||
REQUIRE(group_opt.has_value());
|
||||
auto &group = *group_opt;
|
||||
|
||||
// All four filaments live on extruder 1, on four distinct physical nozzles.
|
||||
std::set<int> distinct_nozzles;
|
||||
for (int f = 0; f < 4; ++f) {
|
||||
REQUIRE(group.get_extruder_id(f) == 1);
|
||||
int nid = group.get_nozzle_id(f);
|
||||
REQUIRE(nid >= 0);
|
||||
distinct_nozzles.insert(nid);
|
||||
}
|
||||
REQUIRE(distinct_nozzles.size() == 4);
|
||||
|
||||
// get_nozzle_id must be stable across layers (no per-layer / selector map here).
|
||||
for (int f = 0; f < 4; ++f) {
|
||||
int base = group.get_nozzle_id(f, -1);
|
||||
REQUIRE(group.get_nozzle_id(f, 0) == base);
|
||||
REQUIRE(group.get_nozzle_id(f, 5) == base);
|
||||
}
|
||||
|
||||
// first-nozzle lookup agrees with the per-layer lookup for a static map.
|
||||
for (int f = 0; f < 4; ++f) {
|
||||
auto first = group.get_first_nozzle_for_filament(f);
|
||||
REQUIRE(first.has_value());
|
||||
REQUIRE(first->extruder_id == 1);
|
||||
REQUIRE(first->group_id == group.get_nozzle_id(f));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("H2C dynamic selector: per-layer nozzle ids reach the g-code surface", "[ToolOrdering][H2C][Dynamic]")
|
||||
{
|
||||
// The per-layer regroup engine
|
||||
// (plan_filament_mapping_and_order_by_combo_ranges -> 4-arg LayeredNozzleGroupResult::create)
|
||||
// produces a *selector* result whose filament->nozzle map varies across layers. This is exactly
|
||||
// what GCode reads for H2C dynamic mode: hotend_id_for_gcode_placeholder /
|
||||
// nozzle_id_for_gcode_placeholder call group->is_support_dynamic_nozzle_map() and, when true,
|
||||
// group->get_nozzle_id(filament, layer) / get_first_nozzle_for_filament(filament). Here we build
|
||||
// the selector result directly (the engine's output shape) and assert those accessors return
|
||||
// per-layer values -- the surface that "goes live" only in dynamic mode. The static path (every
|
||||
// other test above) keeps is_support_dynamic_nozzle_map() == false and a stable nozzle id, so its
|
||||
// g-code is unchanged.
|
||||
|
||||
// H2C-like fleet: extruder 0 = 1 nozzle (group 0), extruder 1 = a 3-nozzle rack (groups 1..3).
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard;
|
||||
n.extruder_id = (g == 0) ? 0 : 1;
|
||||
n.group_id = g;
|
||||
nozzle_list.push_back(n);
|
||||
}
|
||||
|
||||
// Three filaments; filament 2 is reassigned from physical nozzle 2 (layers 0-1) to nozzle 3
|
||||
// (layers 2-3) by the per-layer selector -- the case that sets support_dynamic_nozzle_map.
|
||||
std::vector<std::vector<int>> layer_filament_nozzle_maps = {
|
||||
{0, 1, 2}, // layer 0
|
||||
{0, 1, 2}, // layer 1
|
||||
{0, 1, 3}, // layer 2: filament 2 moved to nozzle 3
|
||||
{0, 1, 3}, // layer 3
|
||||
};
|
||||
std::vector<std::vector<unsigned int>> layer_filament_sequences = {
|
||||
{0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {0, 1, 2},
|
||||
};
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2};
|
||||
|
||||
auto group_opt = LayeredNozzleGroupResult::create(layer_filament_nozzle_maps, nozzle_list, used_filaments, layer_filament_sequences);
|
||||
REQUIRE(group_opt.has_value());
|
||||
auto &group = *group_opt;
|
||||
|
||||
// The selector is active: a filament maps to more than one physical nozzle across layers.
|
||||
REQUIRE(group.is_support_dynamic_nozzle_map());
|
||||
|
||||
// Per-layer hotend/nozzle ids -- the values the dynamic g-code placeholders emit.
|
||||
REQUIRE(group.get_nozzle_id(2, 0) == 2);
|
||||
REQUIRE(group.get_nozzle_id(2, 1) == 2);
|
||||
REQUIRE(group.get_nozzle_id(2, 2) == 3); // reassigned on layer 2
|
||||
REQUIRE(group.get_nozzle_id(2, 3) == 3);
|
||||
REQUIRE(group.get_extruder_id(2, 0) == 1);
|
||||
REQUIRE(group.get_extruder_id(2, 2) == 1);
|
||||
|
||||
// Unmoved filaments keep a stable id across layers.
|
||||
REQUIRE(group.get_nozzle_id(0, 0) == 0);
|
||||
REQUIRE(group.get_nozzle_id(0, 3) == 0);
|
||||
REQUIRE(group.get_nozzle_id(1, 0) == 1);
|
||||
REQUIRE(group.get_nozzle_id(1, 3) == 1);
|
||||
|
||||
// first-nozzle lookup (used by the *_first_* placeholders / start g-code) is the first layer's id.
|
||||
auto first2 = group.get_first_nozzle_for_filament(2);
|
||||
REQUIRE(first2.has_value());
|
||||
REQUIRE(first2->group_id == 2);
|
||||
|
||||
// every physical nozzle a filament visits is reported (3mf metadata / nozzle_diameters_by_nozzle_id).
|
||||
std::set<int> fil2_nozzles;
|
||||
for (const auto &n : group.get_nozzles_for_filament(2))
|
||||
fil2_nozzles.insert(n.group_id);
|
||||
REQUIRE(fil2_nozzles == std::set<int>({2, 3}));
|
||||
}
|
||||
|
||||
TEST_CASE("Multi-nozzle reorder tolerates a filament with no nozzle (RL-48)", "[ToolOrdering][H2C][Dynamic]")
|
||||
{
|
||||
// The per-layer engine can hand reorder_filaments_for_multi_nozzle_extruder a group result that
|
||||
// resolves no nozzle for a layer's filament (a degenerate/malformed input where a layer references
|
||||
// a filament index outside the grouping map). Unguarded, that dereferences std::max_element() on an
|
||||
// empty extruder set (SIGSEGV). The guard must instead emit each layer's filaments in order and
|
||||
// return, so a bad input degrades gracefully rather than crashing.
|
||||
auto nozzle_list = single_nozzle_per_extruder(2);
|
||||
std::vector<int> filament_nozzle_map = {0}; // map only covers filament 0
|
||||
auto group_opt = LayeredNozzleGroupResult::create(filament_nozzle_map, nozzle_list, std::vector<unsigned int>{0});
|
||||
REQUIRE(group_opt.has_value());
|
||||
|
||||
std::vector<unsigned int> filament_lists = {3}; // filament 3 resolves to no nozzle
|
||||
std::vector<std::vector<unsigned int>> layer_filaments = {{3}, {3}};
|
||||
std::vector<std::vector<std::vector<float>>> flush_matrix(2, {{0.f}}); // unused on the guard path
|
||||
std::vector<std::vector<unsigned int>> sequences;
|
||||
|
||||
REQUIRE_NOTHROW(reorder_filaments_for_multi_nozzle_extruder(filament_lists, *group_opt, layer_filaments, flush_matrix, nullptr, &sequences));
|
||||
// Each layer still gets a valid sequence (its own filaments) — no reorder, no crash.
|
||||
REQUIRE(sequences.size() == layer_filaments.size());
|
||||
REQUIRE(sequences[0] == std::vector<unsigned int>{3});
|
||||
REQUIRE(sequences[1] == std::vector<unsigned int>{3});
|
||||
}
|
||||
|
||||
// The round-robin build_multi_nozzle_group_result adapter was superseded by the
|
||||
// nozzle-centric FilamentGroup engine (get_recommended_filament_maps now decides nozzle co-location
|
||||
// by flush cost, not round-robin). The two former pipeline tests are dropped:
|
||||
// * H2C multi-nozzle physical-nozzle resolution (6-arg create) is covered above by the
|
||||
// "H2C multi-nozzle: filaments get distinct nozzles" case;
|
||||
// * the single-nozzle "nozzle id == extruder id" degradation is covered above by the
|
||||
// "Single-nozzle grouping" case (build_default_nozzle_list + 3-arg create is the exact path the
|
||||
// gate-closed branch and by-object fallback use);
|
||||
// * end-to-end H2C/H2D grouping co-location is now pinned by the filament_group golden suite
|
||||
// (tests/filament_group, config_b/config_c).
|
||||
|
||||
TEST_CASE("extruder_nozzle_stats round-trips through save/parse", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// The per-extruder nozzle inventory must survive save_extruder_nozzle_stats_to_string ->
|
||||
// get_extruder_nozzle_stats unchanged, so printer presets and 3mf projects persist it.
|
||||
std::vector<std::map<NozzleVolumeType, int>> stats = {
|
||||
{{nvtStandard, 1}}, // extruder 0: single standard nozzle
|
||||
{{nvtStandard, 5}, {nvtHighFlow, 1}}, // extruder 1: 6-nozzle mixed cluster
|
||||
};
|
||||
REQUIRE(get_extruder_nozzle_stats(save_extruder_nozzle_stats_to_string(stats)) == stats);
|
||||
}
|
||||
|
||||
// The filament-change-time model (MultiNozzleUtils::simulate_filament_change_time) is self-contained
|
||||
// analytic code with no slicing-pipeline caller yet; these fixtures pin its numeric output so future
|
||||
// changes and its first consumer (the filament_group golden harness) build on a locked model. Expected
|
||||
// values are hand-traced through the AMS -> selector -> extruder transport model.
|
||||
TEST_CASE("Filament-change-time model matches the BBS analytic simulation", "[MultiNozzle][H2C][ChangeTime]")
|
||||
{
|
||||
using Catch::Matchers::WithinAbs;
|
||||
|
||||
// Load/unload constants mirror the golden config_c change_time_params
|
||||
// (selector 1/1, standard 3/2): a selector move costs 1, a full AMS load 3 / unload 2.
|
||||
FilamentChangeTimeParams params;
|
||||
params.selector_load_time = 1.0f;
|
||||
params.selector_unload_time = 1.0f;
|
||||
params.standard_load_time = 3.0f;
|
||||
params.standard_unload_time = 2.0f;
|
||||
|
||||
// One extruder carrying one physical nozzle (nozzle id == extruder id == 0).
|
||||
std::vector<NozzleInfo> nozzle_list(1);
|
||||
nozzle_list[0].diameter = "0.4";
|
||||
nozzle_list[0].volume_type = nvtStandard;
|
||||
nozzle_list[0].extruder_id = 0;
|
||||
nozzle_list[0].group_id = 0;
|
||||
|
||||
// Two filaments in distinct AMS groups, printed in the order A, B, A on nozzle 0.
|
||||
std::vector<int> logical_filaments = {0, 1};
|
||||
std::vector<int> group_of_filament = {0, 1};
|
||||
std::vector<int> filament_change_seq = {0, 1, 0};
|
||||
std::vector<int> nozzle_change_seq = {0, 0, 0};
|
||||
|
||||
SECTION("no AMS pre-load: each change is a full AMS<->extruder transport")
|
||||
{
|
||||
auto r = simulate_filament_change_time(
|
||||
logical_filaments, nozzle_list, filament_change_seq, nozzle_change_seq,
|
||||
group_of_filament, params, /*ams_preload_enabled=*/{}, /*calc_sliced_time=*/true);
|
||||
// load0(3) + [unload0(2)+load1(3)] + [unload1(2)+load0(3)] = 13
|
||||
REQUIRE_THAT(r.actual_time, WithinAbs(13.0, 1e-6));
|
||||
// Single nozzle, no selector overlap => slicer estimate equals the actual time.
|
||||
REQUIRE_THAT(r.sliced_time, WithinAbs(13.0, 1e-6));
|
||||
}
|
||||
|
||||
SECTION("AMS pre-load overlaps transport, shrinking the actual time")
|
||||
{
|
||||
std::vector<bool> preload = {true, true};
|
||||
auto r = simulate_filament_change_time(
|
||||
logical_filaments, nozzle_list, filament_change_seq, nozzle_change_seq,
|
||||
group_of_filament, params, preload, /*calc_sliced_time=*/false);
|
||||
// Pre-loading the next filament into the selector runs in parallel with the current
|
||||
// extruder move, so the selector<->extruder legs dominate: 3 + (1+1) + (1+1) = 7.
|
||||
REQUIRE_THAT(r.actual_time, WithinAbs(7.0, 1e-6));
|
||||
}
|
||||
|
||||
SECTION("degenerate inputs return zero")
|
||||
{
|
||||
auto r = simulate_filament_change_time({}, nozzle_list, filament_change_seq,
|
||||
nozzle_change_seq, {}, params);
|
||||
REQUIRE_THAT(r.actual_time, WithinAbs(0.0, 1e-6));
|
||||
REQUIRE_THAT(r.sliced_time, WithinAbs(0.0, 1e-6));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("NozzleStatusRecorder tracks nozzle/extruder occupancy", "[MultiNozzle][H2C][ChangeTime]")
|
||||
{
|
||||
NozzleStatusRecorder rec;
|
||||
REQUIRE(rec.is_nozzle_empty(0));
|
||||
REQUIRE(rec.get_filament_in_nozzle(0) == -1);
|
||||
REQUIRE(rec.get_nozzle_in_extruder(0) == -1);
|
||||
|
||||
rec.set_nozzle_status(2, 5, 1); // nozzle 2 holds filament 5, mounted on extruder 1
|
||||
REQUIRE_FALSE(rec.is_nozzle_empty(2));
|
||||
REQUIRE(rec.get_filament_in_nozzle(2) == 5);
|
||||
REQUIRE(rec.get_nozzle_in_extruder(1) == 2);
|
||||
|
||||
rec.clear_nozzle_status(2);
|
||||
REQUIRE(rec.is_nozzle_empty(2));
|
||||
REQUIRE(rec.get_filament_in_nozzle(2) == -1);
|
||||
// Clearing a nozzle leaves the extruder->nozzle association intact.
|
||||
REQUIRE(rec.get_nozzle_in_extruder(1) == 2);
|
||||
}
|
||||
|
||||
TEST_CASE("Hybrid nozzle stats resolve to concrete volume types", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// Extruder 0 is Standard-only; extruder 1 carries a mixed Standard + High Flow inventory
|
||||
// (the "Hybrid" flow selection). The write-back pipeline persists get_volume_map(), so the
|
||||
// result must always carry concrete per-filament volume types, never the Hybrid seed.
|
||||
auto stats = get_extruder_nozzle_stats({"Standard#1", "Standard#1|High Flow#1"});
|
||||
REQUIRE(stats.size() == 2);
|
||||
REQUIRE(stats[1].size() == 2);
|
||||
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2};
|
||||
std::vector<int> filament_map = {0, 1, 1}; // 0-based extruder ids
|
||||
std::vector<int> volume_requests = {(int) nvtStandard, (int) nvtHighFlow, (int) nvtStandard};
|
||||
std::vector<int> nozzle_requests = {0, 1, 2}; // distinct logical nozzles
|
||||
|
||||
auto group = LayeredNozzleGroupResult::create(used_filaments, filament_map, volume_requests, nozzle_requests, stats, 0.4f);
|
||||
REQUIRE(group.has_value());
|
||||
|
||||
auto volume_map = group->get_volume_map();
|
||||
REQUIRE(volume_map == volume_requests);
|
||||
for (auto fid : used_filaments)
|
||||
REQUIRE(volume_map[fid] != (int) nvtHybrid);
|
||||
|
||||
// The Hybrid seed itself matches no physical nozzle: such a request is unsatisfiable.
|
||||
std::vector<int> hybrid_requests = {(int) nvtStandard, (int) nvtHybrid, (int) nvtStandard};
|
||||
REQUIRE_FALSE(LayeredNozzleGroupResult::create(used_filaments, filament_map, hybrid_requests, nozzle_requests, stats, 0.4f).has_value());
|
||||
}
|
||||
|
||||
TEST_CASE("update_used_filament_values merges only used filaments", "[ToolOrdering][H2C]")
|
||||
{
|
||||
// The config write-back merges the engine's per-filament values over the config baseline:
|
||||
// used filaments adopt the engine value, unused filaments keep their config assignment.
|
||||
std::vector<int> old_values = {1, 1, 2, 1};
|
||||
std::vector<int> new_values = {2, 2, 1, 2};
|
||||
std::vector<unsigned int> used = {0, 2};
|
||||
|
||||
auto merged = FilamentGroupUtils::update_used_filament_values(old_values, new_values, used);
|
||||
REQUIRE(merged == std::vector<int>{2, 1, 1, 1});
|
||||
|
||||
// No used filaments => the config baseline is returned untouched.
|
||||
REQUIRE(FilamentGroupUtils::update_used_filament_values(old_values, new_values, {}) == old_values);
|
||||
}
|
||||
|
||||
TEST_CASE("Print config-index resolvers pick per-filament Hybrid slots", "[Print][H2C]")
|
||||
{
|
||||
// A 2-extruder printer whose second extruder is Hybrid (Standard + High Flow nozzles).
|
||||
// The preset-style variant columns carry one column per (extruder x volume type); apply()
|
||||
// expands them to the 3-slot layout [e1-Std, e2-Std, e2-HF].
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("outer_wall_speed", true)->values = {30., 200., 50., 500.};
|
||||
|
||||
// Three filaments: 0 -> extruder 1 (Std), 1 -> extruder 2 (Std), 2 -> extruder 2 (High Flow).
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard, (int) nvtHighFlow};
|
||||
|
||||
Model model;
|
||||
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
|
||||
// Stub grouping result mirroring the maps above: one nozzle per (extruder, volume type).
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
{
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard; n.extruder_id = 0; n.group_id = 0; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtStandard; n.extruder_id = 1; n.group_id = 1; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtHighFlow; n.extruder_id = 1; n.group_id = 2; nozzle_list.push_back(n);
|
||||
}
|
||||
std::vector<unsigned int> used_filaments = {0, 1, 2};
|
||||
auto group = LayeredNozzleGroupResult::create(std::vector<int>{0, 1, 2}, nozzle_list, used_filaments);
|
||||
REQUIRE(group.has_value());
|
||||
print.set_nozzle_group_result(std::make_shared<LayeredNozzleGroupResult>(*group));
|
||||
|
||||
// The write-back re-expands the config and refreshes the resolver caches.
|
||||
print.update_filament_maps_to_config({1, 2, 2}, {(int) nvtStandard, (int) nvtStandard, (int) nvtHighFlow}, {0, 1, 2});
|
||||
|
||||
// The expansion must have produced the 3-slot layout the resolvers index into.
|
||||
const auto ®ion_config = print.default_region_config();
|
||||
REQUIRE(region_config.print_extruder_variant.values ==
|
||||
std::vector<std::string>({"Direct Drive Standard", "Direct Drive Standard", "Direct Drive High Flow"}));
|
||||
REQUIRE(region_config.print_extruder_id.values == std::vector<int>({1, 2, 2}));
|
||||
|
||||
SECTION("each filament resolves to its own (extruder x volume type) slot") {
|
||||
REQUIRE(print.get_nozzle_config_index(0, 0) == 0); // extruder 1, Standard
|
||||
REQUIRE(print.get_nozzle_config_index(1, 0) == 1); // extruder 2, Standard
|
||||
REQUIRE(print.get_nozzle_config_index(2, 0) == 2); // extruder 2, High Flow
|
||||
}
|
||||
|
||||
SECTION("without a group result the resolver falls back to the filament's extruder slot") {
|
||||
print.set_nozzle_group_result(nullptr);
|
||||
REQUIRE(print.get_nozzle_config_index(0, 0) == 0);
|
||||
REQUIRE(print.get_nozzle_config_index(1, 0) == 1);
|
||||
REQUIRE(print.get_nozzle_config_index(2, 0) == 1); // extruder slot, not the High Flow slot
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Re-applying an unchanged config after slicing keeps the result valid", "[Print][H2C]")
|
||||
{
|
||||
// apply() rebuilds m_config.filament_map_2 to the real per-filament slot map, while the
|
||||
// incoming full config only ever carries the ConfigDef default for it. The engine-derived
|
||||
// key must therefore be kept out of the apply diff: the GUI re-applies right after slicing
|
||||
// completes, and a phantom filament_map_2 diff would invalidate every freshly sliced result
|
||||
// on any multi-extruder printer.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard, (int) nvtHighFlow};
|
||||
|
||||
Model model;
|
||||
ModelObject *object = model.add_object("cube", "", make_cube(20, 20, 20));
|
||||
object->add_instance()->set_offset(Vec3d(100., 100., 0.));
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
|
||||
auto status = print.apply(model, config);
|
||||
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
}
|
||||
|
||||
TEST_CASE("normalize_nozzle_map_per_layer makes per-filament assignments gap-free", "[MultiNozzle][H2C][Dynamic]")
|
||||
{
|
||||
SECTION("gaps inherit the last used nozzle, entries on used layers stay untouched") {
|
||||
// Filament 1 extrudes on layers 0 (nozzle 1) and 3 (nozzle 2); the planner leaves stale
|
||||
// entries on the layers in between.
|
||||
std::vector<std::vector<int>> maps = {
|
||||
{0, 1},
|
||||
{0, -1}, // filament 1 idle
|
||||
{0, -1}, // filament 1 idle
|
||||
{0, 2},
|
||||
};
|
||||
std::vector<std::vector<unsigned int>> filaments = {{0, 1}, {0}, {0}, {0, 1}};
|
||||
|
||||
normalize_nozzle_map_per_layer(maps, filaments);
|
||||
|
||||
REQUIRE(maps[0] == std::vector<int>({0, 1}));
|
||||
REQUIRE(maps[1] == std::vector<int>({0, 1})); // carried forward
|
||||
REQUIRE(maps[2] == std::vector<int>({0, 1})); // carried forward
|
||||
REQUIRE(maps[3] == std::vector<int>({0, 2})); // used layer untouched
|
||||
}
|
||||
|
||||
SECTION("layers before a filament's first use inherit its first nozzle") {
|
||||
std::vector<std::vector<int>> maps = {
|
||||
{0, -1},
|
||||
{0, -1},
|
||||
{0, 3}, // filament 1 first extrudes here
|
||||
};
|
||||
std::vector<std::vector<unsigned int>> filaments = {{0}, {0}, {0, 1}};
|
||||
|
||||
normalize_nozzle_map_per_layer(maps, filaments);
|
||||
|
||||
REQUIRE(maps[0] == std::vector<int>({0, 3})); // back-filled
|
||||
REQUIRE(maps[1] == std::vector<int>({0, 3})); // back-filled
|
||||
REQUIRE(maps[2] == std::vector<int>({0, 3}));
|
||||
}
|
||||
|
||||
SECTION("empty and ragged inputs are safe no-ops") {
|
||||
std::vector<std::vector<int>> empty_maps;
|
||||
std::vector<std::vector<unsigned int>> no_filaments;
|
||||
REQUIRE_NOTHROW(normalize_nozzle_map_per_layer(empty_maps, no_filaments));
|
||||
REQUIRE(empty_maps.empty());
|
||||
|
||||
// Rows of different widths and a filament list shorter than the map list.
|
||||
std::vector<std::vector<int>> ragged = {{0}, {0, 1, 2}};
|
||||
std::vector<std::vector<unsigned int>> short_filaments = {{0}};
|
||||
REQUIRE_NOTHROW(normalize_nozzle_map_per_layer(ragged, short_filaments));
|
||||
REQUIRE(ragged[0] == std::vector<int>({0}));
|
||||
}
|
||||
|
||||
SECTION("a single layer is left unchanged") {
|
||||
std::vector<std::vector<int>> maps = {{2, 1, 0}};
|
||||
std::vector<std::vector<unsigned int>> filaments = {{0, 1, 2}};
|
||||
normalize_nozzle_map_per_layer(maps, filaments);
|
||||
REQUIRE(maps[0] == std::vector<int>({2, 1, 0}));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Stitched sequential blocks resolve per-layer after normalization", "[MultiNozzle][H2C][Dynamic]")
|
||||
{
|
||||
// Shape of the sequential (by-object) stitch: two per-object plan blocks concatenated on one
|
||||
// global layer axis, where the second object's plan moves filament 1 to another physical
|
||||
// nozzle. After normalization the 4-arg create() must detect the migration (selector result)
|
||||
// and resolve stable ids inside each object's layer range.
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
for (int g = 0; g < 3; ++g) {
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard;
|
||||
n.extruder_id = (g == 0) ? 0 : 1;
|
||||
n.group_id = g;
|
||||
nozzle_list.push_back(n);
|
||||
}
|
||||
|
||||
// Object A (layers 0-1): filament 1 on nozzle 1, filament 0 idle until layer 1.
|
||||
// Object B (layers 2-3): filament 1 moved to nozzle 2.
|
||||
std::vector<std::vector<int>> stitched_maps = {
|
||||
{-1, 1},
|
||||
{0, 1},
|
||||
{0, 2},
|
||||
{0, 2},
|
||||
};
|
||||
std::vector<std::vector<unsigned int>> stitched_filaments = {{1}, {0, 1}, {0, 1}, {0, 1}};
|
||||
std::vector<unsigned int> used_filaments = {0, 1};
|
||||
|
||||
normalize_nozzle_map_per_layer(stitched_maps, stitched_filaments);
|
||||
REQUIRE(stitched_maps[0] == std::vector<int>({0, 1})); // filament 0 back-filled to its first nozzle
|
||||
|
||||
auto group_opt = LayeredNozzleGroupResult::create(stitched_maps, nozzle_list, used_filaments, stitched_filaments);
|
||||
REQUIRE(group_opt.has_value());
|
||||
auto &group = *group_opt;
|
||||
|
||||
// A filament on two physical nozzles across the objects => selector result.
|
||||
REQUIRE(group.is_support_dynamic_nozzle_map());
|
||||
REQUIRE(group.get_nozzle_id(1, 0) == 1);
|
||||
REQUIRE(group.get_nozzle_id(1, 1) == 1);
|
||||
REQUIRE(group.get_nozzle_id(1, 2) == 2); // second object's range
|
||||
REQUIRE(group.get_nozzle_id(1, 3) == 2);
|
||||
// The default (out-of-range) map is the first layer's normalized row.
|
||||
REQUIRE(group.get_nozzle_id(0, 999) == 0);
|
||||
REQUIRE(group.get_nozzle_id(1, 999) == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("Sequential selector prints publish a stitched result and cache the plans", "[Print][H2C][Dynamic]")
|
||||
{
|
||||
// By-object + smart filament assign: the by-object branch of Print::process must plan each
|
||||
// object with nozzle-status threading, cache the plans for the g-code export, stitch them
|
||||
// into the published print-wide result, and write the grouping result back to the config
|
||||
// once (per-object orderings must not churn the config).
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtStandard};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard};
|
||||
config.set_key_value("enable_filament_dynamic_map", new ConfigOptionBool(true));
|
||||
config.option<ConfigOptionEnum<FilamentMapMode>>("filament_map_mode", true)->value = FilamentMapMode::fmmAutoForFlush;
|
||||
config.option<ConfigOptionEnum<PrintSequence>>("print_sequence", true)->value = PrintSequence::ByObject;
|
||||
// Export validates flush_volumes_matrix as filaments^2 values per head.
|
||||
config.option<ConfigOptionFloats>("flush_volumes_matrix", true)->values = std::vector<double>(8, 140.);
|
||||
config.option<ConfigOptionFloats>("flush_multiplier", true)->values = {1., 1.};
|
||||
|
||||
Model model;
|
||||
ModelObject *object_a = model.add_object("cube_a", "", make_cube(20, 20, 20));
|
||||
ModelInstance *instance_a = object_a->add_instance();
|
||||
instance_a->set_offset(Vec3d(70., 100., 0.));
|
||||
ModelObject *object_b = model.add_object("cube_b", "", make_cube(20, 20, 20));
|
||||
object_b->config.set_key_value("extruder", new ConfigOptionInt(2));
|
||||
ModelInstance *instance_b = object_b->add_instance();
|
||||
instance_b->set_offset(Vec3d(150., 100., 0.));
|
||||
// The sequential instance ordering keys on arrange_order, which validate() assigns before
|
||||
// process() in the real pipeline (instances tying at 0 get dropped from the ordering);
|
||||
// initialize it here since the test drives process() directly.
|
||||
instance_a->arrange_order = 1;
|
||||
instance_b->arrange_order = 2;
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
REQUIRE(print.objects().size() == 2);
|
||||
print.process();
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
|
||||
auto result = print.get_layered_nozzle_group_result();
|
||||
REQUIRE(result != nullptr);
|
||||
// One cached plan per unique object, and a stitched layer axis spanning both objects.
|
||||
REQUIRE(print.sequential_dynamic_orderings().size() == 2);
|
||||
REQUIRE(result->get_layer_count() > 0);
|
||||
// The write-back mirrors the stitched result's extruder map.
|
||||
REQUIRE(print.config().filament_map.values == result->get_extruder_map(false));
|
||||
// The per-slot filament arrays stay label-consistent whether or not the stitched plan
|
||||
// actually migrated a filament (one slot per filament, plus one per extra variant).
|
||||
REQUIRE(print.config().filament_extruder_variant.values.size() == print.config().filament_self_index.values.size());
|
||||
REQUIRE(print.config().filament_self_index.values.size() >= print.config().filament_map.values.size());
|
||||
|
||||
// Export must consume the cached plans and produce g-code without throwing.
|
||||
boost::filesystem::path gcode_path = boost::filesystem::temp_directory_path() / "orca_seq_dynamic_publish_test.gcode";
|
||||
REQUIRE_NOTHROW(print.export_gcode(gcode_path.string(), nullptr, nullptr));
|
||||
REQUIRE(boost::filesystem::exists(gcode_path));
|
||||
boost::filesystem::remove(gcode_path);
|
||||
}
|
||||
|
||||
TEST_CASE("Per-variant expansion gives migrating filaments one slot per variant", "[PrintConfig][H2C][Dynamic]")
|
||||
{
|
||||
// The selector write-back rebuilds the filament arrays from the grouping result: a filament
|
||||
// that prints through several (extruder x volume type) variants keeps one slot per variant,
|
||||
// and every key grows in lockstep with the self-index / variant labels.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
// Extruder 1 Standard, extruder 2 Hybrid (Standard + High Flow): 3 nozzle slots, 2 extruders.
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
// Two filaments with superset arrays: one column per (filament x variant).
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtHighFlow};
|
||||
config.option<ConfigOptionInts>("filament_self_index", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("nozzle_temperature", true)->values = {220, 230, 240, 250};
|
||||
|
||||
std::set<std::string> key_set = {"filament_self_index", "filament_extruder_variant", "nozzle_temperature"};
|
||||
|
||||
auto make_use = [](ExtruderType et, NozzleVolumeType nvt, int extruder_id) {
|
||||
FilamentVariantUse use;
|
||||
use.extruder_type = et;
|
||||
use.nozzle_volume_type = nvt;
|
||||
use.extruder_id = extruder_id;
|
||||
return use;
|
||||
};
|
||||
|
||||
SECTION("a migrating filament expands, machine slots track each output slot") {
|
||||
std::unordered_map<int, std::vector<FilamentVariantUse>> uses;
|
||||
uses[0] = {make_use(etDirectDrive, nvtStandard, 0), make_use(etDirectDrive, nvtHighFlow, 1)};
|
||||
uses[1] = {make_use(etDirectDrive, nvtHighFlow, 1)};
|
||||
std::vector<int> slot_machine_indices;
|
||||
config.update_filament_config_values_for_multiple_extruders(config, uses, 2, 3, key_set,
|
||||
"filament_self_index", "filament_extruder_variant",
|
||||
&slot_machine_indices);
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>{1, 1, 2});
|
||||
REQUIRE(config.option<ConfigOptionStrings>("filament_extruder_variant")->values ==
|
||||
std::vector<std::string>({"Direct Drive Standard", "Direct Drive High Flow", "Direct Drive High Flow"}));
|
||||
REQUIRE(config.option<ConfigOptionInts>("nozzle_temperature")->values == std::vector<int>{220, 230, 250});
|
||||
// Slot 0 backs onto extruder 1 Standard; slots 1-2 onto extruder 2 High Flow.
|
||||
REQUIRE(slot_machine_indices == std::vector<int>{0, 3, 3});
|
||||
}
|
||||
|
||||
SECTION("filaments absent from the uses fall back to their static assignment") {
|
||||
std::unordered_map<int, std::vector<FilamentVariantUse>> uses;
|
||||
uses[0] = {make_use(etDirectDrive, nvtStandard, 0)};
|
||||
// Filament 1 unrouted: filament_map -> extruder 2 (Hybrid) -> volume map -> High Flow.
|
||||
config.update_filament_config_values_for_multiple_extruders(config, uses, 2, 3, key_set,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
REQUIRE(config.option<ConfigOptionInts>("filament_self_index")->values == std::vector<int>{1, 2});
|
||||
REQUIRE(config.option<ConfigOptionInts>("nozzle_temperature")->values == std::vector<int>{220, 250});
|
||||
}
|
||||
|
||||
SECTION("a mis-sized filament_volume_map is ignored") {
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtHighFlow};
|
||||
std::unordered_map<int, std::vector<FilamentVariantUse>> uses;
|
||||
uses[0] = {make_use(etDirectDrive, nvtStandard, 0)};
|
||||
// Unrouted filament 1 keeps the extruder's own typing (Hybrid folds to Standard).
|
||||
config.update_filament_config_values_for_multiple_extruders(config, uses, 2, 3, key_set,
|
||||
"filament_self_index", "filament_extruder_variant");
|
||||
REQUIRE(config.option<ConfigOptionInts>("nozzle_temperature")->values == std::vector<int>{220, 240});
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Selector write-back expands migrating filaments and survives re-apply", "[Print][H2C][Dynamic]")
|
||||
{
|
||||
// A filament the per-layer plan moves between nozzle variants must end up with one config
|
||||
// slot per variant (so per-layer temperatures/retractions resolve correctly), the extruder
|
||||
// retract overrides must key each slot to its own variant's machine value, and an unchanged
|
||||
// re-apply must reproduce the expansion instead of trimming it back to one slot per
|
||||
// filament — a trim-back would diff the freshly written values and invalidate the result.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
// Three filaments: 0 -> extruder 1 (Std), 1 -> extruder 2 (Std), 2 -> extruder 2, migrating
|
||||
// Standard -> High Flow between layers. Superset arrays: one column per (filament x variant).
|
||||
// filament_type must be sized to the filament count: the variant-use collection (like the
|
||||
// full-config producers) keys the per-filament loop on it.
|
||||
config.option<ConfigOptionStrings>("filament_type", true)->values = {"PLA", "PLA", "PLA"};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard, (int) nvtStandard};
|
||||
config.option<ConfigOptionInts>("filament_self_index", true)->values = {1, 1, 2, 2, 3, 3};
|
||||
config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("nozzle_temperature", true)->values = {200, 210, 220, 230, 240, 250};
|
||||
// The migrating filament's Standard column is nil, so the override merge must fall back to
|
||||
// the machine value of the Standard slot (not the High Flow one).
|
||||
config.option<ConfigOptionFloatsNullable>("filament_retraction_length", true)->values =
|
||||
{0.5, 0.5, 0.6, 0.6, ConfigOptionFloatsNullable::nil_value(), 1.2};
|
||||
config.option<ConfigOptionFloats>("retraction_length", true)->values = {0.8, 0.9, 1.0, 1.1};
|
||||
|
||||
Model model;
|
||||
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
|
||||
// Stub grouping result: nozzles as in the resolver test; filament 2 prints on the Standard
|
||||
// nozzle at layer 0 and on the High Flow nozzle at layer 1.
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
{
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard; n.extruder_id = 0; n.group_id = 0; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtStandard; n.extruder_id = 1; n.group_id = 1; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtHighFlow; n.extruder_id = 1; n.group_id = 2; nozzle_list.push_back(n);
|
||||
}
|
||||
std::vector<std::vector<int>> layer_maps = {{0, 1, 1}, {0, 1, 2}};
|
||||
std::vector<std::vector<unsigned int>> layer_seqs = {{0, 1, 2}, {0, 1, 2}};
|
||||
auto group = LayeredNozzleGroupResult::create(layer_maps, nozzle_list, {0, 1, 2}, layer_seqs);
|
||||
REQUIRE(group.has_value());
|
||||
REQUIRE(group->is_support_dynamic_nozzle_map());
|
||||
print.set_nozzle_group_result(std::make_shared<LayeredNozzleGroupResult>(*group));
|
||||
|
||||
print.update_to_config_by_nozzle_group_result(*group);
|
||||
|
||||
// Filament 2 holds two slots (Standard + High Flow), everything in lockstep.
|
||||
REQUIRE(print.config().filament_map.values == group->get_extruder_map(false));
|
||||
REQUIRE(print.config().filament_self_index.values == std::vector<int>{1, 2, 3, 3});
|
||||
REQUIRE(print.config().nozzle_temperature.values == std::vector<int>{200, 220, 240, 250});
|
||||
// The layer-aware resolver picks the slot matching each layer's variant.
|
||||
REQUIRE(print.get_filament_config_indx(2, 0) == 2);
|
||||
REQUIRE(print.get_filament_config_indx(2, 1) == 3);
|
||||
// Retract overrides: non-nil slots take the filament value; the nil Standard slot of the
|
||||
// migrating filament falls back to its own variant's machine value.
|
||||
const auto &machine_retract = print.full_print_config().option<ConfigOptionFloats>("retraction_length")->values;
|
||||
int f2_std_machine_slot = print.full_print_config().get_index_for_extruder(2, "print_extruder_id", etDirectDrive, nvtStandard,
|
||||
"print_extruder_variant");
|
||||
REQUIRE(f2_std_machine_slot >= 0);
|
||||
const std::vector<double> merged_retract = print.config().retraction_length.values;
|
||||
REQUIRE(merged_retract.size() == 4);
|
||||
REQUIRE_THAT(merged_retract[0], Catch::Matchers::WithinAbs(0.5, 1e-9));
|
||||
REQUIRE_THAT(merged_retract[1], Catch::Matchers::WithinAbs(0.6, 1e-9));
|
||||
REQUIRE_THAT(merged_retract[2], Catch::Matchers::WithinAbs(machine_retract[f2_std_machine_slot], 1e-9));
|
||||
REQUIRE_THAT(merged_retract[3], Catch::Matchers::WithinAbs(1.2, 1e-9));
|
||||
|
||||
// Re-apply the unchanged config: the persisted result must reproduce the exact expansion.
|
||||
auto status = print.apply(model, config);
|
||||
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
|
||||
REQUIRE(print.config().filament_self_index.values == std::vector<int>{1, 2, 3, 3});
|
||||
REQUIRE(print.config().nozzle_temperature.values == std::vector<int>{200, 220, 240, 250});
|
||||
REQUIRE(print.config().retraction_length.values == merged_retract);
|
||||
}
|
||||
|
||||
TEST_CASE("Filaments ordered after a migrator shift columns and the resolver tracks them", "[Print][H2C][Dynamic]")
|
||||
{
|
||||
// When a mid-list filament expands to two columns, every later filament's values move one
|
||||
// column to the right — a raw get_at(filament_id) lands in the migrator's second column.
|
||||
// The layer-aware resolver must return the shifted column for both the expanded filament
|
||||
// arrays and the merged machine overrides.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
// Three filaments: 0 -> extruder 1 (Std), 1 -> extruder 2, migrating Standard -> High Flow
|
||||
// between layers, 2 -> extruder 2 (Std) — ordered AFTER the migrator.
|
||||
config.option<ConfigOptionStrings>("filament_type", true)->values = {"PLA", "PLA", "PLA"};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard, (int) nvtStandard};
|
||||
config.option<ConfigOptionInts>("filament_self_index", true)->values = {1, 1, 2, 2, 3, 3};
|
||||
config.option<ConfigOptionStrings>("filament_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("nozzle_temperature", true)->values = {200, 210, 220, 230, 240, 250};
|
||||
config.option<ConfigOptionFloatsNullable>("filament_retraction_length", true)->values = {0.5, 0.5, 0.7, 0.9, 1.4, 1.4};
|
||||
config.option<ConfigOptionFloats>("retraction_length", true)->values = {0.8, 0.9, 1.0, 1.1};
|
||||
|
||||
Model model;
|
||||
model.add_object("cube", "", make_cube(20, 20, 20))->add_instance();
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
|
||||
std::vector<NozzleInfo> nozzle_list;
|
||||
{
|
||||
NozzleInfo n;
|
||||
n.diameter = "0.4";
|
||||
n.volume_type = nvtStandard; n.extruder_id = 0; n.group_id = 0; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtStandard; n.extruder_id = 1; n.group_id = 1; nozzle_list.push_back(n);
|
||||
n.volume_type = nvtHighFlow; n.extruder_id = 1; n.group_id = 2; nozzle_list.push_back(n);
|
||||
}
|
||||
// Filament 1: Standard nozzle on layer 0, High Flow nozzle on layer 1; filament 2 stays Standard.
|
||||
std::vector<std::vector<int>> layer_maps = {{0, 1, 1}, {0, 2, 1}};
|
||||
std::vector<std::vector<unsigned int>> layer_seqs = {{0, 1, 2}, {0, 1, 2}};
|
||||
auto group = LayeredNozzleGroupResult::create(layer_maps, nozzle_list, {0, 1, 2}, layer_seqs);
|
||||
REQUIRE(group.has_value());
|
||||
REQUIRE(group->is_support_dynamic_nozzle_map());
|
||||
print.set_nozzle_group_result(std::make_shared<LayeredNozzleGroupResult>(*group));
|
||||
|
||||
print.update_to_config_by_nozzle_group_result(*group);
|
||||
|
||||
// Filament 1 holds columns 1-2; filament 2's values shift to column 3.
|
||||
REQUIRE(print.config().filament_self_index.values == std::vector<int>{1, 2, 2, 3});
|
||||
REQUIRE(print.config().nozzle_temperature.values == std::vector<int>{200, 220, 230, 240});
|
||||
// The migrator resolves per layer to its two columns.
|
||||
REQUIRE(print.get_filament_config_indx(1, 0) == 1);
|
||||
REQUIRE(print.get_filament_config_indx(1, 1) == 2);
|
||||
// The filament after it no longer lives at its raw index on any layer.
|
||||
REQUIRE(print.get_filament_config_indx(2, 0) == 3);
|
||||
REQUIRE(print.get_filament_config_indx(2, 1) == 3);
|
||||
// Merged machine override: filament 2's value sits in the shifted column, while a raw
|
||||
// get_at(2) would read the migrator's High Flow column.
|
||||
const std::vector<double> merged = print.config().retraction_length.values;
|
||||
REQUIRE(merged.size() == 4);
|
||||
REQUIRE_THAT(merged[3], Catch::Matchers::WithinAbs(1.4, 1e-9));
|
||||
REQUIRE_THAT(merged[2], Catch::Matchers::WithinAbs(0.9, 1e-9));
|
||||
}
|
||||
|
||||
TEST_CASE("Selector slicing keeps the result valid across re-apply", "[Print][H2C][Dynamic]")
|
||||
{
|
||||
// The dynamic counterpart of the static re-apply test above: a full process() run through
|
||||
// the selector branch (whatever grouping it settles on) must leave the config in a state
|
||||
// the next apply reproduces without invalidating the freshly sliced result.
|
||||
DynamicPrintConfig config = DynamicPrintConfig::full_print_config();
|
||||
config.option<ConfigOptionFloats>("nozzle_diameter", true)->values = {0.4, 0.4};
|
||||
config.option<ConfigOptionStrings>("extruder_nozzle_stats", true)->values = {"Standard#1", "Standard#1|High Flow#2"};
|
||||
config.option<ConfigOptionEnumsGeneric>("extruder_type", true)->values = {etDirectDrive, etDirectDrive};
|
||||
config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type", true)->values = {nvtStandard, nvtHybrid};
|
||||
config.option<ConfigOptionStrings>("extruder_variant_list", true)->values = {"Direct Drive Standard,Direct Drive High Flow",
|
||||
"Direct Drive Standard,Direct Drive High Flow"};
|
||||
config.option<ConfigOptionInts>("print_extruder_id", true)->values = {1, 1, 2, 2};
|
||||
config.option<ConfigOptionStrings>("print_extruder_variant", true)->values = {"Direct Drive Standard", "Direct Drive High Flow",
|
||||
"Direct Drive Standard", "Direct Drive High Flow"};
|
||||
config.option<ConfigOptionFloats>("filament_diameter", true)->values = {1.75, 1.75, 1.75};
|
||||
config.option<ConfigOptionStrings>("filament_colour", true)->values = {"#FF0000", "#00FF00", "#0000FF"};
|
||||
config.option<ConfigOptionInts>("filament_map", true)->values = {1, 2, 2};
|
||||
config.option<ConfigOptionInts>("filament_volume_map", true)->values = {(int) nvtStandard, (int) nvtStandard, (int) nvtHighFlow};
|
||||
config.set_key_value("enable_filament_dynamic_map", new ConfigOptionBool(true));
|
||||
config.option<ConfigOptionEnum<FilamentMapMode>>("filament_map_mode", true)->value = FilamentMapMode::fmmAutoForFlush;
|
||||
|
||||
Model model;
|
||||
ModelObject *object = model.add_object("cube", "", make_cube(20, 20, 20));
|
||||
object->add_instance()->set_offset(Vec3d(100., 100., 0.));
|
||||
|
||||
Print print;
|
||||
print.apply(model, config);
|
||||
print.process();
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
|
||||
auto status = print.apply(model, config);
|
||||
REQUIRE(status != PrintBase::APPLY_STATUS_INVALIDATED);
|
||||
REQUIRE(print.is_step_done(psSlicingFinished));
|
||||
}
|
||||
@@ -1,15 +1,57 @@
|
||||
get_filename_component(_TEST_NAME ${CMAKE_CURRENT_LIST_DIR} NAME)
|
||||
add_executable(${_TEST_NAME}_tests
|
||||
${_TEST_NAME}_tests_main.cpp
|
||||
test_dev_mapping.cpp
|
||||
test_network_versions.cpp
|
||||
test_action_source.cpp
|
||||
test_plugin_host_api.cpp
|
||||
test_plugin_capability_config.cpp
|
||||
test_plugin_config.cpp
|
||||
test_plugin_capabilities_in_use.cpp
|
||||
test_plugin_install.cpp
|
||||
test_plugin_lifecycle.cpp
|
||||
test_slicing_pipeline_bindings.cpp
|
||||
test_slicing_pipeline_config.cpp
|
||||
test_plugin_sort.cpp
|
||||
test_plugin_cloud_metadata.cpp
|
||||
test_plugin_audit.cpp
|
||||
../fff_print/test_helpers.cpp
|
||||
)
|
||||
|
||||
if (MSVC)
|
||||
target_link_libraries(${_TEST_NAME}_tests Setupapi.lib)
|
||||
endif ()
|
||||
|
||||
target_link_libraries(${_TEST_NAME}_tests test_common libslic3r_gui libslic3r Catch2::Catch2WithMain)
|
||||
target_link_libraries(${_TEST_NAME}_tests test_common libslic3r_gui libslic3r pybind11::embed Catch2::Catch2WithMain)
|
||||
set_property(TARGET ${_TEST_NAME}_tests PROPERTY FOLDER "tests")
|
||||
|
||||
orcaslicer_copy_test_dlls()
|
||||
|
||||
if (WIN32)
|
||||
add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_PREFIX_PATH}/libpython" "$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
"${CMAKE_PREFIX_PATH}/libpython/python${_bundled_python_abi}.dll"
|
||||
"${CMAKE_PREFIX_PATH}/libpython/vcruntime140.dll"
|
||||
"${CMAKE_PREFIX_PATH}/libpython/vcruntime140_1.dll"
|
||||
"$<TARGET_FILE_DIR:${_TEST_NAME}_tests>"
|
||||
COMMENT "Copying Python runtime for slic3rutils plugin host API tests"
|
||||
VERBATIM
|
||||
)
|
||||
elseif (APPLE)
|
||||
target_link_options(${_TEST_NAME}_tests PRIVATE
|
||||
"LINKER:-rpath,@executable_path/python/lib")
|
||||
|
||||
add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E rm -rf
|
||||
"$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
"${CMAKE_PREFIX_PATH}/libpython"
|
||||
"$<TARGET_FILE_DIR:${_TEST_NAME}_tests>/python"
|
||||
COMMENT "Copying Python runtime for macOS plugin host API tests"
|
||||
VERBATIM
|
||||
)
|
||||
endif()
|
||||
|
||||
orcaslicer_discover_tests(${_TEST_NAME}_tests)
|
||||
|
||||
39
tests/slic3rutils/plugin_test_utils.hpp
Normal file
39
tests/slic3rutils/plugin_test_utils.hpp
Normal file
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
// Point data_dir() at a throwaway directory for the lifetime of a test and
|
||||
// restore the previous value afterwards, so code under test writes into a
|
||||
// disposable tree and tests don't leak state into each other.
|
||||
struct ScopedDataDir
|
||||
{
|
||||
std::string previous;
|
||||
boost::filesystem::path dir;
|
||||
|
||||
explicit ScopedDataDir(const std::string& tag)
|
||||
{
|
||||
namespace fs = boost::filesystem;
|
||||
previous = data_dir();
|
||||
dir = fs::temp_directory_path() / fs::unique_path("orca-" + tag + "-%%%%-%%%%");
|
||||
fs::create_directories(dir);
|
||||
set_data_dir(dir.string());
|
||||
}
|
||||
|
||||
~ScopedDataDir()
|
||||
{
|
||||
set_data_dir(previous);
|
||||
boost::system::error_code ec;
|
||||
boost::filesystem::remove_all(dir, ec);
|
||||
}
|
||||
|
||||
ScopedDataDir(const ScopedDataDir&) = delete;
|
||||
ScopedDataDir& operator=(const ScopedDataDir&) = delete;
|
||||
};
|
||||
|
||||
} // namespace Slic3r
|
||||
53
tests/slic3rutils/python_test_support.hpp
Normal file
53
tests/slic3rutils/python_test_support.hpp
Normal file
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
// Shared embedded-interpreter bootstrap for slic3rutils tests that need a live Python
|
||||
// interpreter (test_plugin_host_api.cpp, test_slicing_pipeline_bindings.cpp, ...).
|
||||
#include <boost/dll/runtime_symbol_info.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <memory.h>
|
||||
#include <stdexcept>
|
||||
#include <pybind11/embed.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include <slic3r/plugin/PythonPluginBridge.hpp>
|
||||
|
||||
namespace {
|
||||
|
||||
void ensure_python_initialized()
|
||||
{
|
||||
if (Py_IsInitialized())
|
||||
return;
|
||||
|
||||
static std::unique_ptr<pybind11::scoped_interpreter> interpreter;
|
||||
|
||||
PyConfig config;
|
||||
PyConfig_InitPythonConfig(&config);
|
||||
config.parse_argv = 0;
|
||||
|
||||
const auto python_home = boost::dll::program_location().parent_path() / "python";
|
||||
|
||||
if (boost::filesystem::exists(python_home)) {
|
||||
const std::string home = python_home.string();
|
||||
const PyStatus status = PyConfig_SetBytesString(&config, &config.home, home.c_str());
|
||||
|
||||
if (PyStatus_Exception(status)) {
|
||||
const char* message = status.err_msg ? status.err_msg : "Failed to set Python home";
|
||||
PyConfig_Clear(&config);
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
}
|
||||
|
||||
interpreter = std::make_unique<pybind11::scoped_interpreter>(&config);
|
||||
}
|
||||
|
||||
pybind11::module_ import_orca_module()
|
||||
{
|
||||
ensure_python_initialized();
|
||||
|
||||
// Force PythonPluginBridge.cpp into the test binary so the embedded
|
||||
// PYBIND11_EMBEDDED_MODULE(orca, ...) registration is available.
|
||||
(void) Slic3r::PythonPluginBridge::instance();
|
||||
return pybind11::module_::import("orca");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
55
tests/slic3rutils/test_action_source.cpp
Normal file
55
tests/slic3rutils/test_action_source.cpp
Normal file
@@ -0,0 +1,55 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
using Slic3r::GUI::AppAction;
|
||||
using Slic3r::GUI::AppActionRunResult;
|
||||
using Slic3r::GUI::ActionRegistry;
|
||||
|
||||
namespace {
|
||||
|
||||
// AppAction is abstract; this minimal concrete action lets the tests exercise its
|
||||
// constructor-composed identity without involving a plugin runner.
|
||||
class TestAppAction final : public AppAction
|
||||
{
|
||||
public:
|
||||
TestAppAction() : AppAction("test", "Action title", "src-key", "Action source") {}
|
||||
|
||||
AppActionRunResult run() const override { return {}; }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("AppAction composes a stable id from prefix:title:source_key", "[speeddial][actions]")
|
||||
{
|
||||
CHECK(AppAction::compose_id("test", "Action title", "src-key") == "test:Action title:src-key");
|
||||
// source_key (not the display name) carries identity, so it is the third field.
|
||||
CHECK(AppAction::compose_id("script", "Do Thing", "pack.py") == "script:Do Thing:pack.py");
|
||||
}
|
||||
|
||||
TEST_CASE("AppAction definitions are immutable after construction", "[speeddial][actions]")
|
||||
{
|
||||
using StringAccessor = const std::string& (AppAction::*)() const;
|
||||
|
||||
STATIC_CHECK(std::is_same_v<decltype(&AppAction::id), StringAccessor>);
|
||||
STATIC_CHECK(std::is_same_v<decltype(&AppAction::title), StringAccessor>);
|
||||
STATIC_CHECK(std::is_same_v<decltype(&AppAction::source_key), StringAccessor>);
|
||||
STATIC_CHECK(std::is_same_v<decltype(&AppAction::source_name), StringAccessor>);
|
||||
|
||||
const TestAppAction action;
|
||||
CHECK(action.id() == "test:Action title:src-key");
|
||||
CHECK(action.title() == "Action title");
|
||||
CHECK(action.source_key() == "src-key");
|
||||
CHECK(action.source_name() == "Action source");
|
||||
}
|
||||
|
||||
TEST_CASE("ActionRegistry takes exclusive ownership of published actions", "[speeddial][actions]")
|
||||
{
|
||||
using ExpectedUpsert = void (ActionRegistry::*)(std::unique_ptr<AppAction>);
|
||||
|
||||
STATIC_CHECK(std::is_same_v<decltype(&ActionRegistry::upsert), ExpectedUpsert>);
|
||||
}
|
||||
195
tests/slic3rutils/test_dev_mapping.cpp
Normal file
195
tests/slic3rutils/test_dev_mapping.cpp
Normal file
@@ -0,0 +1,195 @@
|
||||
// Match the include environment that libslic3r_gui TUs get from pchheader.hpp: Windows.h with
|
||||
// WIN32_LEAN_AND_MEAN/NOMINMAX must come first so rpcndr.h's `byte` is processed before <cstddef>
|
||||
// makes std::byte a competing candidate (otherwise the Windows COM headers pulled in via
|
||||
// DeviceManager.hpp error with an ambiguous `byte`). wx/timer.h must precede DeviceManager.hpp,
|
||||
// which includes DeviceErrorDialog.hpp (uses wxTimerEvent) before its own wx/timer.h include.
|
||||
#ifdef WIN32
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <Windows.h>
|
||||
#endif
|
||||
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <wx/timer.h>
|
||||
|
||||
#include "slic3r/GUI/DeviceManager.hpp"
|
||||
#include "slic3r/GUI/DeviceCore/DevMapping.h"
|
||||
#include "slic3r/GUI/DeviceCore/DevFilaSystem.h"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
using json = nlohmann::json;
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("Switch-bound AMS trays map to the left extruder", "[DevMapping]")
|
||||
{
|
||||
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
|
||||
|
||||
// aux bit 29 = Filament Track Switch installed (DevFilaSwitch.cpp:69-77)
|
||||
obj.GetFilaSwitch()->ParseFilaSwitchInfo(json::parse(R"({"aux":"20000000"})"));
|
||||
REQUIRE(obj.GetFilaSwitch()->IsInstalled());
|
||||
|
||||
// info bits: 0-3 type(1=AMS), 8-11 extruder(0xE=switch-bound), 24-27 bind_switch_in(0)
|
||||
// tray_exist_bits bit 0 marks AMS 0 / tray 0 present so the mapping result survives the
|
||||
// is_exists check in is_valid_mapping_result (DevFilaSystem.cpp:769).
|
||||
// tray_info_idx/tray_type are intentionally omitted: the tray parse resolves the display
|
||||
// filament type via MachineObject::setting_id_to_type(), which reads the GUI preset bundle
|
||||
// (wxGetApp().preset_bundle) — unavailable in this headless unit test. The tray filament
|
||||
// type (only needed for the type-match below) is set directly after the parse instead.
|
||||
json print_push = json::parse(R"({
|
||||
"ams": {
|
||||
"tray_exist_bits": "1",
|
||||
"ams": [ {
|
||||
"id": "0",
|
||||
"info": "00000E01",
|
||||
"tray": [ { "id": "0", "tray_color": "FF0000FF" } ]
|
||||
} ]
|
||||
}
|
||||
})");
|
||||
DevFilaSystemParser::ParseV1_0(print_push, &obj, obj.GetFilaSystem().get(), false);
|
||||
|
||||
const auto& ams_list = obj.GetFilaSystem()->GetAmsList();
|
||||
REQUIRE(ams_list.count("0") == 1);
|
||||
REQUIRE(ams_list.at("0")->GetBindedExtruderSet().count(MAIN_EXTRUDER_ID) == 1);
|
||||
REQUIRE(ams_list.at("0")->GetBindedExtruderSet().count(DEPUTY_EXTRUDER_ID) == 1);
|
||||
|
||||
DevAmsTray* tray = obj.GetFilaSystem()->GetAmsTray("0", "0");
|
||||
REQUIRE(tray != nullptr);
|
||||
tray->m_fila_type = "PLA";
|
||||
|
||||
FilamentInfo fila;
|
||||
fila.id = 0;
|
||||
fila.type = "PLA";
|
||||
fila.color = "FF0000FF";
|
||||
|
||||
std::vector<FilamentInfo> result;
|
||||
std::vector<bool> map_opt(4, false); // MappingOption: LEFT_AMS,RIGHT_AMS,LEFT_EXT,RIGHT_EXT (DevMapping.h:13-19)
|
||||
map_opt[MappingOption::USE_LEFT_AMS] = true;
|
||||
|
||||
DevMappingUtil::ams_filament_mapping(&obj, {fila}, result, map_opt, {}, false);
|
||||
|
||||
// A switch-bound AMS feeds BOTH extruders, so a left-only mapping request
|
||||
// must still land the filament on the AMS tray.
|
||||
REQUIRE(result.size() == 1);
|
||||
CHECK(result[0].tray_id == 0);
|
||||
CHECK(result[0].ams_id == "0");
|
||||
}
|
||||
|
||||
TEST_CASE("Without a switch the binding set equals the single bound extruder", "[DevMapping]")
|
||||
{
|
||||
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
|
||||
REQUIRE_FALSE(obj.GetFilaSwitch()->IsInstalled());
|
||||
|
||||
// AMS 0: info extruder nibble = MAIN (right). AMS 1: nibble = DEPUTY (left).
|
||||
// AMS 2: no "info" key at all (old X1/P1 firmware) -> must default to MAIN.
|
||||
// tray_exist_bits: bit ams_id*4+tray_id -> 0x111 marks tray 0 of each AMS.
|
||||
json print_push = json::parse(R"({
|
||||
"ams": {
|
||||
"tray_exist_bits": "111",
|
||||
"ams": [
|
||||
{ "id": "0", "info": "00000001", "tray": [ { "id": "0", "tray_color": "FF0000FF" } ] },
|
||||
{ "id": "1", "info": "00000101", "tray": [ { "id": "0", "tray_color": "00FF00FF" } ] },
|
||||
{ "id": "2", "tray": [ { "id": "0", "tray_color": "0000FFFF" } ] }
|
||||
]
|
||||
}
|
||||
})");
|
||||
DevFilaSystemParser::ParseV1_0(print_push, &obj, obj.GetFilaSystem().get(), false);
|
||||
|
||||
// The invariant that keeps the binding-set mapping filter behavior-preserving for
|
||||
// ordinary printers: GetBindedExtruderSet() == { GetExtruderId() }, info key or not.
|
||||
const auto& ams_list = obj.GetFilaSystem()->GetAmsList();
|
||||
REQUIRE(ams_list.count("0") == 1);
|
||||
REQUIRE(ams_list.count("1") == 1);
|
||||
REQUIRE(ams_list.count("2") == 1);
|
||||
for (const char* id : {"0", "1", "2"}) {
|
||||
const auto& ams = ams_list.at(id);
|
||||
INFO("ams " << id);
|
||||
REQUIRE(ams->GetBindedExtruderSet().size() == 1);
|
||||
REQUIRE(ams->GetBindedExtruderSet().count(ams->GetExtruderId()) == 1);
|
||||
}
|
||||
REQUIRE(ams_list.at("0")->GetExtruderId() == MAIN_EXTRUDER_ID);
|
||||
REQUIRE(ams_list.at("1")->GetExtruderId() == DEPUTY_EXTRUDER_ID);
|
||||
REQUIRE(ams_list.at("2")->GetExtruderId() == MAIN_EXTRUDER_ID);
|
||||
|
||||
for (const char* id : {"0", "1", "2"}) {
|
||||
DevAmsTray* tray = obj.GetFilaSystem()->GetAmsTray(id, "0");
|
||||
REQUIRE(tray != nullptr);
|
||||
tray->m_fila_type = "PLA";
|
||||
}
|
||||
|
||||
// A left-only request must exclude the MAIN-bound AMSes: the red filament exactly
|
||||
// matches AMS 0's red tray, so landing anywhere but AMS 1 (or unmapped) means the
|
||||
// exclusion is broken.
|
||||
FilamentInfo fila;
|
||||
fila.id = 0;
|
||||
fila.type = "PLA";
|
||||
fila.color = "FF0000FF";
|
||||
|
||||
std::vector<FilamentInfo> result;
|
||||
std::vector<bool> map_opt(4, false);
|
||||
map_opt[MappingOption::USE_LEFT_AMS] = true;
|
||||
DevMappingUtil::ams_filament_mapping(&obj, {fila}, result, map_opt, {}, false);
|
||||
REQUIRE(result.size() == 1);
|
||||
CHECK(result[0].ams_id != "0");
|
||||
CHECK(result[0].ams_id != "2");
|
||||
|
||||
// The mirrored right-only request maps to the exact-match MAIN-bound AMS.
|
||||
result.clear();
|
||||
map_opt[MappingOption::USE_LEFT_AMS] = false;
|
||||
map_opt[MappingOption::USE_RIGHT_AMS] = true;
|
||||
DevMappingUtil::ams_filament_mapping(&obj, {fila}, result, map_opt, {}, false);
|
||||
REQUIRE(result.size() == 1);
|
||||
CHECK(result[0].ams_id == "0");
|
||||
}
|
||||
|
||||
TEST_CASE("Switch-bound AMS with an invalid track is excluded from mapping", "[DevMapping]")
|
||||
{
|
||||
MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
|
||||
obj.GetFilaSwitch()->ParseFilaSwitchInfo(json::parse(R"({"aux":"20000000"})"));
|
||||
REQUIRE(obj.GetFilaSwitch()->IsInstalled());
|
||||
|
||||
// info bits 24-27 = 0xF: switch-bound (0xE) but the input track is not yet valid -
|
||||
// the transient while the device is still homing the switch. The AMS must survive
|
||||
// (display keeps working) with an EMPTY binding set that excludes it from mapping.
|
||||
json print_push = json::parse(R"({
|
||||
"ams": {
|
||||
"tray_exist_bits": "1",
|
||||
"ams": [ { "id": "0", "info": "0F000E01", "tray": [ { "id": "0", "tray_color": "FF0000FF" } ] } ]
|
||||
}
|
||||
})");
|
||||
DevFilaSystemParser::ParseV1_0(print_push, &obj, obj.GetFilaSystem().get(), false);
|
||||
|
||||
const auto& ams_list = obj.GetFilaSystem()->GetAmsList();
|
||||
REQUIRE(ams_list.count("0") == 1);
|
||||
REQUIRE(ams_list.at("0")->GetBindedExtruderSet().empty());
|
||||
REQUIRE_FALSE(ams_list.at("0")->GetSwitcherPos().has_value());
|
||||
REQUIRE_FALSE(obj.GetFilaSwitch()->IsReady());
|
||||
|
||||
DevAmsTray* tray = obj.GetFilaSystem()->GetAmsTray("0", "0");
|
||||
REQUIRE(tray != nullptr);
|
||||
tray->m_fila_type = "PLA";
|
||||
|
||||
FilamentInfo fila;
|
||||
fila.id = 0;
|
||||
fila.type = "PLA";
|
||||
fila.color = "FF0000FF";
|
||||
|
||||
std::vector<FilamentInfo> result;
|
||||
std::vector<bool> map_opt(4, false);
|
||||
map_opt[MappingOption::USE_LEFT_AMS] = true;
|
||||
map_opt[MappingOption::USE_RIGHT_AMS] = true;
|
||||
DevMappingUtil::ams_filament_mapping(&obj, {fila}, result, map_opt, {}, false);
|
||||
REQUIRE(result.size() == 1);
|
||||
CHECK(result[0].tray_id == -1);
|
||||
|
||||
// Without the switch, the same 0xE AMS is dropped from the list entirely.
|
||||
MachineObject obj_no_switch(nullptr, nullptr, "test", "test_dev", "127.0.0.1");
|
||||
REQUIRE_FALSE(obj_no_switch.GetFilaSwitch()->IsInstalled());
|
||||
DevFilaSystemParser::ParseV1_0(print_push, &obj_no_switch, obj_no_switch.GetFilaSystem().get(), false);
|
||||
REQUIRE(obj_no_switch.GetFilaSystem()->GetAmsList().count("0") == 0);
|
||||
}
|
||||
199
tests/slic3rutils/test_network_versions.cpp
Normal file
199
tests/slic3rutils/test_network_versions.cpp
Normal file
@@ -0,0 +1,199 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
|
||||
#include "libslic3r/Utils.hpp"
|
||||
#include "slic3r/Utils/bambu_networking.hpp"
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
// Platform naming used by BBLNetworkPlugin::scan_plugin_versions().
|
||||
#if defined(_MSC_VER) || defined(_WIN32)
|
||||
static const char* PLUGIN_PREFIX = "bambu_networking_";
|
||||
static const char* PLUGIN_EXT = ".dll";
|
||||
#elif defined(__WXMAC__) || defined(__APPLE__)
|
||||
static const char* PLUGIN_PREFIX = "libbambu_networking_";
|
||||
static const char* PLUGIN_EXT = ".dylib";
|
||||
#else
|
||||
static const char* PLUGIN_PREFIX = "libbambu_networking_";
|
||||
static const char* PLUGIN_EXT = ".so";
|
||||
#endif
|
||||
|
||||
struct PluginFolderFixture
|
||||
{
|
||||
fs::path root;
|
||||
std::string previous_data_dir;
|
||||
|
||||
PluginFolderFixture()
|
||||
{
|
||||
previous_data_dir = data_dir();
|
||||
root = fs::temp_directory_path() / fs::unique_path("orca-netver-%%%%%%%%");
|
||||
fs::create_directories(root / "plugins");
|
||||
set_data_dir(root.string());
|
||||
}
|
||||
|
||||
~PluginFolderFixture()
|
||||
{
|
||||
set_data_dir(previous_data_dir);
|
||||
boost::system::error_code ec;
|
||||
fs::remove_all(root, ec);
|
||||
}
|
||||
|
||||
void add_plugin(const std::string& version)
|
||||
{
|
||||
boost::nowide::ofstream f((root / "plugins" / (PLUGIN_PREFIX + version + PLUGIN_EXT)).string());
|
||||
f << "stub";
|
||||
}
|
||||
};
|
||||
|
||||
int count_version(const std::vector<NetworkLibraryVersionInfo>& versions, const std::string& v)
|
||||
{
|
||||
int n = 0;
|
||||
for (const auto& info : versions)
|
||||
if (info.version == v)
|
||||
++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Series and managed classification", "[NetworkVersions]")
|
||||
{
|
||||
// The AA.BB.CC series is the stored identity of every modern build.
|
||||
CHECK(network_plugin_series("02.08.01.53") == "02.08.01");
|
||||
CHECK(network_plugin_series("02.08.01") == "02.08.01"); // idempotent
|
||||
CHECK(network_plugin_series("02.08.01_custom") == "02.08.01");
|
||||
CHECK(network_plugin_series("02.08.01.52-dev") == "02.08.01");
|
||||
CHECK(network_plugin_series(BAMBU_NETWORK_AGENT_VERSION_LEGACY) == BAMBU_NETWORK_AGENT_VERSION_LEGACY);
|
||||
CHECK(network_plugin_series("").empty());
|
||||
|
||||
// Only pure dotted-numeric builds collapse into their series entry; legacy and any
|
||||
// custom-named build keep their own identity.
|
||||
CHECK(is_series_managed_version("02.08.01"));
|
||||
CHECK(is_series_managed_version("02.08.01.53"));
|
||||
CHECK_FALSE(is_series_managed_version("02.08.01_custom"));
|
||||
CHECK_FALSE(is_series_managed_version("02.08.01.52-dev"));
|
||||
CHECK_FALSE(is_series_managed_version(BAMBU_NETWORK_AGENT_VERSION_LEGACY));
|
||||
CHECK_FALSE(is_series_managed_version(""));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(PluginFolderFixture, "Managed builds fold into the series; customs are surfaced", "[NetworkVersions]")
|
||||
{
|
||||
add_plugin("02.08.01.55"); // managed, same series -> folded into the 02.08.01 row
|
||||
add_plugin("02.09.00.10"); // managed, unknown series -> not listed
|
||||
add_plugin("02.03.00.62"); // managed, series no longer whitelisted -> not listed
|
||||
add_plugin("02.08.01_custom"); // custom, whitelisted series -> listed under it
|
||||
add_plugin("02.08.01.52-dev"); // custom (dash-suffixed), whitelisted series -> listed
|
||||
|
||||
auto versions = get_all_available_versions();
|
||||
|
||||
// The specific managed build never gets its own row - the series represents it.
|
||||
REQUIRE(count_version(versions, "02.08.01.55") == 0);
|
||||
REQUIRE(count_version(versions, "02.08.01") == 1);
|
||||
REQUIRE(count_version(versions, "02.09.00.10") == 0);
|
||||
REQUIRE(count_version(versions, "02.03.00.62") == 0);
|
||||
// Custom-named builds are distinct files kept under their own name.
|
||||
REQUIRE(count_version(versions, "02.08.01_custom") == 1);
|
||||
REQUIRE(count_version(versions, "02.08.01.52-dev") == 1);
|
||||
|
||||
// Newest series first, its customs nested under it (suffix sort: "" < ".52-dev" < "_custom"),
|
||||
// legacy last.
|
||||
REQUIRE(versions[0].version == "02.08.01");
|
||||
REQUIRE(versions[1].version == "02.08.01.52-dev");
|
||||
REQUIRE(versions[2].version == "02.08.01_custom");
|
||||
REQUIRE(versions.back().version == BAMBU_NETWORK_AGENT_VERSION_LEGACY);
|
||||
|
||||
// Customs sort/render nested under their series (non-empty suffix, base = the series).
|
||||
REQUIRE(versions[1].base_version == "02.08.01");
|
||||
REQUIRE_FALSE(versions[1].suffix.empty());
|
||||
REQUIRE(versions[2].base_version == "02.08.01");
|
||||
REQUIRE_FALSE(versions[2].suffix.empty());
|
||||
|
||||
// "(Latest)" is the series row, never a nested custom build.
|
||||
REQUIRE(versions[0].suffix.empty());
|
||||
REQUIRE(versions[0].is_latest);
|
||||
REQUIRE_FALSE(versions[1].is_latest);
|
||||
REQUIRE_FALSE(versions[2].is_latest);
|
||||
|
||||
// The stored default that drives download and update-check decisions is now the series.
|
||||
REQUIRE(std::string(get_latest_network_version()) == "02.08.01");
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(PluginFolderFixture, "Only the loaded series is marked installed", "[NetworkVersions]")
|
||||
{
|
||||
add_plugin("02.08.01.55");
|
||||
add_plugin("02.08.01_custom");
|
||||
|
||||
// The loaded plug-in reports its full build (02.08.01.55); the series row is what gets marked.
|
||||
{
|
||||
auto versions = get_all_available_versions("02.08.01.55");
|
||||
int marked = 0;
|
||||
for (const auto& info : versions)
|
||||
if (info.is_loaded) { ++marked; REQUIRE(info.version == "02.08.01"); }
|
||||
REQUIRE(marked == 1);
|
||||
}
|
||||
|
||||
// A loaded custom build matches its own row, never the bare series.
|
||||
{
|
||||
auto versions = get_all_available_versions("02.08.01_custom");
|
||||
int marked = 0;
|
||||
for (const auto& info : versions)
|
||||
if (info.is_loaded) { ++marked; REQUIRE(info.version == "02.08.01_custom"); }
|
||||
REQUIRE(marked == 1);
|
||||
}
|
||||
|
||||
// Nothing loaded marks nothing, even though libraries are on disk.
|
||||
for (const auto& info : get_all_available_versions(""))
|
||||
REQUIRE_FALSE(info.is_loaded);
|
||||
}
|
||||
|
||||
TEST_CASE("Only whitelisted series pass the load gate", "[NetworkVersions]")
|
||||
{
|
||||
// The whitelisted series, its builds, and custom-named builds of that series.
|
||||
REQUIRE(is_supported_network_version("02.08.01"));
|
||||
REQUIRE(is_supported_network_version("02.08.01.52"));
|
||||
REQUIRE(is_supported_network_version("02.08.01.55"));
|
||||
REQUIRE(is_supported_network_version("02.08.01_custom"));
|
||||
REQUIRE(is_supported_network_version("02.08.01.52-dev"));
|
||||
REQUIRE(is_supported_network_version(BAMBU_NETWORK_AGENT_VERSION_LEGACY));
|
||||
|
||||
// Series whitelisted by previous Orca releases - their ABI no longer matches.
|
||||
REQUIRE_FALSE(is_supported_network_version("02.03.00.62"));
|
||||
REQUIRE_FALSE(is_supported_network_version("02.01.01.52"));
|
||||
REQUIRE_FALSE(is_supported_network_version("02.00.02.50"));
|
||||
|
||||
// Unknown series, legacy siblings, and malformed values.
|
||||
REQUIRE_FALSE(is_supported_network_version("02.09.00.10"));
|
||||
std::string legacy = BAMBU_NETWORK_AGENT_VERSION_LEGACY;
|
||||
std::string legacy_sibling = legacy.substr(0, 9) + (legacy.substr(9) == "99" ? "98" : "99");
|
||||
REQUIRE_FALSE(is_supported_network_version(legacy_sibling));
|
||||
REQUIRE_FALSE(is_supported_network_version(""));
|
||||
REQUIRE_FALSE(is_supported_network_version("02.08"));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(PluginFolderFixture, "Legacy series never adopts discovered builds", "[NetworkVersions]")
|
||||
{
|
||||
// A different build of the legacy series must not be surfaced: is_legacy_version()
|
||||
// matches exactly, so it would be loaded with the modern struct layout.
|
||||
std::string legacy = BAMBU_NETWORK_AGENT_VERSION_LEGACY;
|
||||
std::string legacy_sibling = legacy.substr(0, 9) + (legacy.substr(9) == "99" ? "98" : "99");
|
||||
add_plugin(legacy_sibling);
|
||||
|
||||
auto versions = get_all_available_versions();
|
||||
|
||||
REQUIRE(count_version(versions, legacy_sibling) == 0);
|
||||
REQUIRE(count_version(versions, legacy) == 1);
|
||||
|
||||
// With nothing else on disk, the series holds "(Latest)" even though its library is
|
||||
// not installed.
|
||||
for (const auto& info : versions) {
|
||||
if (info.version == "02.08.01") {
|
||||
REQUIRE(info.is_latest);
|
||||
REQUIRE_FALSE(info.is_loaded);
|
||||
}
|
||||
}
|
||||
}
|
||||
187
tests/slic3rutils/test_plugin_audit.cpp
Normal file
187
tests/slic3rutils/test_plugin_audit.cpp
Normal file
@@ -0,0 +1,187 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <libslic3r/libslic3r.h> // GCODEVIEWER_APP_KEY, SLIC3R_APP_KEY (via libslic3r_version.h)
|
||||
#include <slic3r/plugin/PluginAuditManager.hpp>
|
||||
#include <slic3r/Utils/OrcaCloudServiceAgent.hpp> // secret_constants::USER_SECRET_FILENAME
|
||||
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
// Seed the deny registry with the same list install_hook() uses. Both draw from
|
||||
// PluginAuditManager::default_denied_filenames(), so the test and production seeding cannot
|
||||
// drift apart. The registry is a process singleton, so repeated seeding only appends harmless
|
||||
// duplicates; matching is unaffected.
|
||||
void seed_denied_names()
|
||||
{
|
||||
PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
for (const auto& name : PluginAuditManager::default_denied_filenames())
|
||||
mgr.add_denied_filename(name);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Plugin audit denies app config and token filenames anywhere", "[audit]")
|
||||
{
|
||||
seed_denied_names();
|
||||
const PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
|
||||
SECTION("the seeded names are denied by their base name")
|
||||
{
|
||||
CHECK(mgr.is_denied_filename(fs::path(SLIC3R_APP_KEY ".conf")));
|
||||
CHECK(mgr.is_denied_filename(fs::path(GCODEVIEWER_APP_KEY ".conf")));
|
||||
CHECK(mgr.is_denied_filename(fs::path(SLIC3R_APP_KEY ".ini")));
|
||||
CHECK(mgr.is_denied_filename(fs::path(GCODEVIEWER_APP_KEY ".ini")));
|
||||
CHECK(mgr.is_denied_filename(fs::path(secret_constants::USER_SECRET_FILENAME)));
|
||||
}
|
||||
|
||||
SECTION("companions holding the same secrets are denied by the prefix rule")
|
||||
{
|
||||
CHECK(mgr.is_denied_filename(fs::path(SLIC3R_APP_KEY ".conf.bak")));
|
||||
CHECK(mgr.is_denied_filename(fs::path(std::string(secret_constants::USER_SECRET_FILENAME) + ".tmp")));
|
||||
// Windows alternate data streams share the same base name.
|
||||
CHECK(mgr.is_denied_filename(fs::path(SLIC3R_APP_KEY ".conf:stream")));
|
||||
}
|
||||
|
||||
SECTION("the denial ignores the directory the file lives in")
|
||||
{
|
||||
CHECK(mgr.is_denied_filename(fs::path("/tmp") / (SLIC3R_APP_KEY ".conf")));
|
||||
CHECK(mgr.is_denied_filename(fs::path("/some/plugin/dir") / (SLIC3R_APP_KEY ".conf")));
|
||||
// Traversal is handled for free: filename() of the path below is already the denied name.
|
||||
CHECK(mgr.is_denied_filename(fs::path(data_dir()) / "plugins" / ".." / (SLIC3R_APP_KEY ".conf")));
|
||||
}
|
||||
|
||||
SECTION("matching is case-insensitive on every platform")
|
||||
{
|
||||
CHECK(mgr.is_denied_filename(fs::path("orcaslicer.conf")));
|
||||
CHECK(mgr.is_denied_filename(fs::path("ORCASLICER.CONF")));
|
||||
CHECK(mgr.is_denied_filename(fs::path("ORCA_REFRESH_TOKEN.SEC")));
|
||||
}
|
||||
|
||||
SECTION("an unrelated name that merely shares a stem is not denied")
|
||||
{
|
||||
// The prefix is the full registered name ("OrcaSlicer.conf"), not the stem "OrcaSlicer",
|
||||
// so a sibling file with a different extension/suffix stays allowed.
|
||||
CHECK_FALSE(mgr.is_denied_filename(fs::path(data_dir()) / (SLIC3R_APP_KEY "_other.txt")));
|
||||
CHECK_FALSE(mgr.is_denied_filename(fs::path(data_dir()) / (SLIC3R_APP_KEY ".json")));
|
||||
CHECK_FALSE(mgr.is_denied_filename(fs::path("orca_refresh_token.txt")));
|
||||
}
|
||||
|
||||
SECTION("an empty path is not denied")
|
||||
{
|
||||
CHECK_FALSE(mgr.is_denied_filename(fs::path()));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin audit deny beats allowed roots and the Loading read exemption", "[audit]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-audit-deny");
|
||||
seed_denied_names();
|
||||
|
||||
PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
// Reproduce install_hook()'s grant: data_dir() is a global allowed root, so both the app
|
||||
// config and the token would otherwise be reachable simply by living inside it.
|
||||
mgr.add_global_allowed_root(data_dir());
|
||||
|
||||
// Enter a plugin context. The deny must hold in Loading mode, which every scope runs in.
|
||||
ScopedPluginAuditContext ctx("test_plugin", "", PluginAuditManager::AuditMode::Loading);
|
||||
|
||||
const fs::path conf = fs::path(data_dir()) / (SLIC3R_APP_KEY ".conf");
|
||||
const fs::path token = fs::path(data_dir()) / secret_constants::USER_SECRET_FILENAME;
|
||||
|
||||
SECTION("a non-denied file inside the allowed root is writable (root really grants writes)")
|
||||
{
|
||||
AuditDecision decision = mgr.check_open((fs::path(data_dir()) / "plugin_data.txt").string(), "w");
|
||||
CHECK(decision.allowed);
|
||||
}
|
||||
|
||||
SECTION("writing the app config is blocked despite data_dir() being allowed")
|
||||
{
|
||||
AuditDecision decision = mgr.check_open(conf.string(), "w");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
CHECK(decision.reason == "denied filename");
|
||||
}
|
||||
|
||||
SECTION("reading the app config is blocked even though Loading exempts reads")
|
||||
{
|
||||
// Without the deny, a read in Loading mode short-circuits to allow. The deny sits above
|
||||
// that exemption, so this must still be blocked.
|
||||
AuditDecision decision = mgr.check_open(conf.string(), "r");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
CHECK(decision.reason == "denied filename");
|
||||
}
|
||||
|
||||
SECTION("reading the cloud refresh token is blocked in Loading mode")
|
||||
{
|
||||
AuditDecision decision = mgr.check_open(token.string(), "r");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
}
|
||||
|
||||
SECTION("the token staging companion (.tmp) is blocked too")
|
||||
{
|
||||
AuditDecision decision = mgr.check_open((token.string() + ".tmp"), "w");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
}
|
||||
|
||||
SECTION("a traversal path resolving to the config is blocked")
|
||||
{
|
||||
const fs::path traversal = fs::path(data_dir()) / "plugins" / ".." / (SLIC3R_APP_KEY ".conf");
|
||||
AuditDecision decision = mgr.check_open(traversal.string(), "r");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin audit deny beats a plugin's own scoped root", "[audit]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-audit-scoped");
|
||||
seed_denied_names();
|
||||
|
||||
PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
|
||||
// A plugin's private directory, granted as a scoped root while it runs.
|
||||
const fs::path plugin_dir = fs::path(data_dir()) / "plugins" / "test_plugin";
|
||||
fs::create_directories(plugin_dir);
|
||||
|
||||
ScopedPluginAuditContext ctx("test_plugin", "", PluginAuditManager::AuditMode::Loading);
|
||||
mgr.add_scoped_allowed_root(plugin_dir);
|
||||
|
||||
SECTION("the plugin's own non-denied file opens for read and write")
|
||||
{
|
||||
const std::string own_file = (plugin_dir / "state.json").string();
|
||||
CHECK(mgr.check_open(own_file, "r").allowed);
|
||||
CHECK(mgr.check_open(own_file, "w").allowed);
|
||||
}
|
||||
|
||||
SECTION("a denied name stashed inside the plugin's own root is still blocked")
|
||||
{
|
||||
const std::string smuggled = (plugin_dir / (SLIC3R_APP_KEY ".conf")).string();
|
||||
AuditDecision decision = mgr.check_open(smuggled, "w");
|
||||
CHECK_FALSE(decision.allowed);
|
||||
CHECK(decision.reason == "denied filename");
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin audit does not constrain non-plugin code", "[audit]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-audit-noplugin");
|
||||
seed_denied_names();
|
||||
|
||||
PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
mgr.clear_current_plugin(); // no plugin context: this is OrcaSlicer's own C++/internal Python
|
||||
|
||||
const fs::path conf = fs::path(data_dir()) / (SLIC3R_APP_KEY ".conf");
|
||||
|
||||
// The name is still recognised as denied...
|
||||
CHECK(mgr.is_denied_filename(conf));
|
||||
// ...but with no current plugin the access check allows it: denies constrain plugin code only.
|
||||
CHECK(mgr.check_open(conf.string(), "w").allowed);
|
||||
CHECK(mgr.check_open(conf.string(), "r").allowed);
|
||||
}
|
||||
74
tests/slic3rutils/test_plugin_capabilities_in_use.cpp
Normal file
74
tests/slic3rutils/test_plugin_capabilities_in_use.cpp
Normal file
@@ -0,0 +1,74 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Preset.hpp>
|
||||
#include <libslic3r/PrintConfig.hpp>
|
||||
#include <slic3r/plugin/PluginResolver.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Slic3r;
|
||||
|
||||
namespace {
|
||||
|
||||
// A print preset carrying a "plugins" manifest and the one plugin-backed print option.
|
||||
Preset make_print_preset(const std::vector<std::string>& manifest, const std::vector<std::string>& pipeline)
|
||||
{
|
||||
Preset preset(Preset::TYPE_PRINT, "test-print");
|
||||
const std::unique_ptr<DynamicPrintConfig> defaults(
|
||||
DynamicPrintConfig::new_from_defaults_keys({"plugins", "slicing_pipeline_plugin"}));
|
||||
preset.config = *defaults;
|
||||
preset.config.option<ConfigOptionStrings>("plugins")->values = manifest;
|
||||
preset.config.option<ConfigOptionStrings>("slicing_pipeline_plugin")->values = pipeline;
|
||||
return preset;
|
||||
}
|
||||
|
||||
std::vector<std::string> capability_names(const std::vector<PluginCapabilityRef>& refs)
|
||||
{
|
||||
std::vector<std::string> names;
|
||||
for (const PluginCapabilityRef& ref : refs)
|
||||
names.push_back(ref.capability_name);
|
||||
return names;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("referenced_capabilities keeps only manifest entries an option points at", "[PluginResolver]")
|
||||
{
|
||||
// CapB is declared in the manifest but no option references it, so it is not in use.
|
||||
const Preset preset = make_print_preset({"acme;;CapA", "acme;;CapB"}, {"CapA"});
|
||||
|
||||
CHECK(capability_names(referenced_capabilities(Preset::TYPE_PRINT, preset)) == std::vector<std::string>{"CapA"});
|
||||
}
|
||||
|
||||
TEST_CASE("referenced_capabilities matches every value of a vector option", "[PluginResolver]")
|
||||
{
|
||||
const Preset preset = make_print_preset({"acme;;CapA", "acme;;CapB", "acme;;CapC"}, {"CapA", "CapC"});
|
||||
|
||||
CHECK(capability_names(referenced_capabilities(Preset::TYPE_PRINT, preset)) ==
|
||||
std::vector<std::string>{"CapA", "CapC"});
|
||||
}
|
||||
|
||||
TEST_CASE("referenced_capabilities is empty when the manifest is empty", "[PluginResolver]")
|
||||
{
|
||||
const Preset preset = make_print_preset({}, {"CapA"});
|
||||
|
||||
CHECK(referenced_capabilities(Preset::TYPE_PRINT, preset).empty());
|
||||
}
|
||||
|
||||
TEST_CASE("referenced_capabilities ignores untracked preset types", "[PluginResolver]")
|
||||
{
|
||||
Preset preset = make_print_preset({"acme;;CapA"}, {"CapA"});
|
||||
preset.type = Preset::TYPE_SLA_PRINT;
|
||||
|
||||
CHECK(referenced_capabilities(Preset::TYPE_SLA_PRINT, preset).empty());
|
||||
}
|
||||
|
||||
TEST_CASE("referenced_capabilities skips malformed manifest entries", "[PluginResolver]")
|
||||
{
|
||||
// parse_capability_ref rejects entries that are not "name;uuid;capability".
|
||||
const Preset preset = make_print_preset({"garbage", "acme;;CapA"}, {"CapA"});
|
||||
|
||||
CHECK(capability_names(referenced_capabilities(Preset::TYPE_PRINT, preset)) == std::vector<std::string>{"CapA"});
|
||||
}
|
||||
449
tests/slic3rutils/test_plugin_capability_config.cpp
Normal file
449
tests/slic3rutils/test_plugin_capability_config.cpp
Normal file
@@ -0,0 +1,449 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginConfig.hpp>
|
||||
#include <slic3r/plugin/PluginManager.hpp>
|
||||
#include <slic3r/plugin/PythonInterpreter.hpp>
|
||||
#include <slic3r/plugin/PythonPluginBridge.hpp>
|
||||
#include <slic3r/plugin/PythonPluginInterface.hpp>
|
||||
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <pybind11/embed.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace py = pybind11;
|
||||
using namespace Slic3r;
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
// Brings the plugin system up for the duration of one test and tears it down at the end — same
|
||||
// idiom as ScopedPluginManager in test_plugin_lifecycle.cpp, and for the same reason: shutdown()
|
||||
// logs via boost::log, so it must run before boost::log tears down its thread-local storage, not be
|
||||
// left to a static destructor at process exit.
|
||||
//
|
||||
// Needed here (unlike a bare pybind11::scoped_interpreter): has_config_ui()/get_config_ui()/
|
||||
// get_name()/etc. all cross PyPluginCommonTrampoline's ORCA_PY_OVERRIDE_AUDITED, which refuses to
|
||||
// call into Python unless PythonInterpreter::instance() itself reports initialized (see
|
||||
// PythonGILState). A bare interpreter never sets that flag, so every trampoline call would report
|
||||
// "Python interpreter is shutting down" even though Python was perfectly alive.
|
||||
//
|
||||
// initialize() leaves the GIL released (production code re-acquires it per call via PythonGILState);
|
||||
// every TEST_CASE below pairs this with a py::gil_scoped_acquire, declared second so it releases
|
||||
// before this destructor's shutdown() runs.
|
||||
struct ScopedPluginManager
|
||||
{
|
||||
bool initialized = PluginManager::instance().initialize();
|
||||
|
||||
~ScopedPluginManager()
|
||||
{
|
||||
PluginManager::instance().shutdown();
|
||||
PythonInterpreter::instance().shutdown();
|
||||
}
|
||||
};
|
||||
|
||||
py::module_ import_orca_module()
|
||||
{
|
||||
(void) PythonPluginBridge::instance(); // force the embedded module registration into the binary
|
||||
return py::module_::import("orca");
|
||||
}
|
||||
|
||||
// Builds a Python capability the way PluginLoader does: the audit identity is stamped on by the
|
||||
// host, never supplied by the plugin, and it scopes every config call to this one capability.
|
||||
py::object make_capability(const std::string& class_name,
|
||||
const std::string& body,
|
||||
const std::string& plugin_key,
|
||||
const std::string& capability_name,
|
||||
PluginCapabilityType type = PluginCapabilityType::Script)
|
||||
{
|
||||
// Import first: it brings the interpreter up, and any py:: object built before it would touch a
|
||||
// Python that does not exist yet.
|
||||
py::module_ orca = import_orca_module();
|
||||
|
||||
py::dict globals;
|
||||
globals["orca"] = orca;
|
||||
|
||||
py::exec("class " + class_name + "(orca.PythonPluginBase):\n" + body, globals);
|
||||
py::object instance = globals[class_name.c_str()]();
|
||||
|
||||
if (!plugin_key.empty()) {
|
||||
auto iface = instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
|
||||
iface->set_audit_plugin_key(plugin_key);
|
||||
iface->set_resolved_identity(capability_name, type);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
std::shared_ptr<PluginCapabilityInterface> as_interface(const py::object& instance)
|
||||
{
|
||||
return instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
|
||||
}
|
||||
|
||||
// The Python API writes through the PluginManager singleton, so that is where assertions read from.
|
||||
PluginConfig& host_config() { return PluginManager::instance().get_config(); }
|
||||
|
||||
// The Python config API speaks JSON text, not dicts; these helpers keep the tests in terms of values.
|
||||
json py_get_config(const py::object& cap) { return json::parse(cap.attr("get_config")().cast<std::string>()); }
|
||||
|
||||
bool py_save_config(const py::object& cap, const json& value) { return cap.attr("save_config")(value.dump()).cast<bool>(); }
|
||||
|
||||
PluginCapabilityId capability_id(PluginCapabilityType type, const char* name, const char* plugin_key)
|
||||
{
|
||||
return {type, name, plugin_key};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Capability config API is exposed on every Python capability", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
py::module_ orca = import_orca_module();
|
||||
REQUIRE(py::hasattr(orca, "PythonPluginBase"));
|
||||
|
||||
py::object base = orca.attr("PythonPluginBase");
|
||||
// Host-provided: every capability has a config, so there is no hook to opt out of being
|
||||
// configurable.
|
||||
CHECK(py::hasattr(base, "get_config"));
|
||||
CHECK(py::hasattr(base, "save_config"));
|
||||
CHECK(py::hasattr(base, "get_config_version"));
|
||||
// Plugin-provided (the host calls these). All optional.
|
||||
CHECK(py::hasattr(base, "has_config_ui"));
|
||||
CHECK(py::hasattr(base, "get_config_ui"));
|
||||
CHECK(py::hasattr(base, "get_default_config"));
|
||||
|
||||
// Config is reached only through the capability, never as a free orca.config.* function, so a
|
||||
// capability cannot name — and cannot touch — a config that is not its own.
|
||||
CHECK_FALSE(py::hasattr(orca, "config"));
|
||||
}
|
||||
|
||||
TEST_CASE("get_config returns only cap_config and save_config persists it", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-roundtrip");
|
||||
host_config().load(); // reset the singleton's in-memory store against the empty temp dir
|
||||
|
||||
py::object cap = make_capability("RoundTripCap", " def get_name(self): return 'cap_a'\n", "plugin_a", "cap_a");
|
||||
|
||||
// Nothing stored yet: the JSON text of an empty object, not None, so a plugin can json.loads() it
|
||||
// unconditionally.
|
||||
py::object initial = cap.attr("get_config")();
|
||||
REQUIRE(py::isinstance<py::str>(initial));
|
||||
CHECK(json::parse(initial.cast<std::string>()) == json::object());
|
||||
CHECK(cap.attr("get_config_version")().cast<std::string>().empty());
|
||||
|
||||
REQUIRE(py_save_config(cap, json{{"speed", 5}, {"name", "fast"}}));
|
||||
|
||||
const auto stored = host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"));
|
||||
REQUIRE(stored);
|
||||
CHECK(stored->id == capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"));
|
||||
CHECK(stored->config == json{{"speed", 5}, {"name", "fast"}});
|
||||
|
||||
// Python reads back exactly cap_config — no host metadata.
|
||||
const json reloaded = py_get_config(cap);
|
||||
CHECK(reloaded.size() == 2);
|
||||
CHECK(reloaded.contains("speed"));
|
||||
CHECK_FALSE(reloaded.contains("plugin_key"));
|
||||
CHECK_FALSE(reloaded.contains("capability"));
|
||||
CHECK_FALSE(reloaded.contains("cap_config"));
|
||||
CHECK_FALSE(reloaded.contains("plugin_version"));
|
||||
}
|
||||
|
||||
TEST_CASE("save_config rejects a string that is not valid JSON", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-badjson");
|
||||
host_config().load();
|
||||
|
||||
py::object cap = make_capability("BadJsonCap", " def get_name(self): return 'cap_a'\n", "plugin_a", "cap_a");
|
||||
|
||||
REQUIRE(py_save_config(cap, json{{"keep", "me"}}));
|
||||
|
||||
// Refusing unparseable text must leave the previously stored config alone.
|
||||
CHECK_FALSE(cap.attr("save_config")("{not json").cast<bool>());
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"keep", "me"}});
|
||||
}
|
||||
|
||||
TEST_CASE("Saving one capability's config does not touch another's", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-isolation");
|
||||
host_config().load();
|
||||
|
||||
const std::string body = " def get_name(self): return 'cap'\n";
|
||||
// Same capability name under two plugins, plus a second capability of plugin_a: each addresses
|
||||
// only the entry matching its own stamped identity.
|
||||
py::object a_cap1 = make_capability("IsoCapA1", body, "plugin_a", "cap_a");
|
||||
py::object a_cap2 = make_capability("IsoCapA2", body, "plugin_a", "cap_b");
|
||||
py::object b_cap1 = make_capability("IsoCapB1", body, "plugin_b", "cap_a");
|
||||
|
||||
REQUIRE(py_save_config(a_cap1, json{{"value", 1}}));
|
||||
REQUIRE(py_save_config(a_cap2, json{{"value", 2}}));
|
||||
REQUIRE(py_save_config(b_cap1, json{{"value", 3}}));
|
||||
|
||||
REQUIRE(py_save_config(a_cap1, json{{"value", 99}}));
|
||||
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"value", 99}});
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_b", "plugin_a"))->config == json{{"value", 2}});
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_b"))->config == json{{"value", 3}});
|
||||
|
||||
// A shared name under one plugin must remain isolated when the capability type differs.
|
||||
py::object importer = make_capability("IsoCapImporter", body, "plugin_a", "cap_a", PluginCapabilityType::Importer);
|
||||
REQUIRE(py_save_config(importer, json{{"value", 4}}));
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"value", 99}});
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Importer, "cap_a", "plugin_a"))->config == json{{"value", 4}});
|
||||
|
||||
host_config().load();
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"value", 99}});
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Importer, "cap_a", "plugin_a"))->config == json{{"value", 4}});
|
||||
|
||||
CHECK(py_get_config(a_cap2).at("value") == 2);
|
||||
CHECK(py_get_config(b_cap1).at("value") == 3);
|
||||
}
|
||||
|
||||
TEST_CASE("Config API refuses a capability the host never materialized", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-unowned");
|
||||
host_config().load();
|
||||
|
||||
// No audit identity: never loaded by the host, so it has no config to address. Refused rather
|
||||
// than served from, or written to, some arbitrary entry.
|
||||
py::object orphan = make_capability("OrphanCap", " def get_name(self): return 'cap'\n", "", "");
|
||||
|
||||
CHECK_THROWS(orphan.attr("get_config")());
|
||||
CHECK_THROWS(orphan.attr("get_config_version")());
|
||||
CHECK_THROWS(orphan.attr("save_config")(json::object().dump()));
|
||||
}
|
||||
|
||||
TEST_CASE("Custom config UI hooks dispatch to the Python override", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
py::object cap = make_capability("CustomUiCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def has_config_ui(self): return True\n"
|
||||
" def get_config_ui(self): return '<p>hello</p>'\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
CHECK(iface->has_config_ui());
|
||||
CHECK(iface->get_config_ui() == "<p>hello</p>");
|
||||
}
|
||||
|
||||
TEST_CASE("A capability that omits the config UI hooks gets the default editor", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-bare");
|
||||
host_config().load();
|
||||
|
||||
// Both hooks are optional and only choose the editor: a capability that overrides neither is
|
||||
// still configurable, it just gets the host's JSON editor. There is no way to opt out.
|
||||
py::object bare = make_capability("BareCap", " def get_name(self): return 'cap_a'\n", "plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(bare);
|
||||
REQUIRE(iface);
|
||||
CHECK_FALSE(iface->has_config_ui()); // -> default JSON editor
|
||||
CHECK(iface->get_config_ui().empty());
|
||||
|
||||
REQUIRE(py_save_config(bare, json{{"speed", 5}}));
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"speed", 5}});
|
||||
}
|
||||
|
||||
TEST_CASE("get_default_config supplies the value Restore defaults writes back", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
SECTION("not overridden -> an empty config")
|
||||
{
|
||||
// Already "restore defaults" for a capability that keeps its stored config sparse and applies
|
||||
// its own defaults on read.
|
||||
py::object bare = make_capability("NoDefaultsCap", " def get_name(self): return 'cap_a'\n", "plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(bare);
|
||||
REQUIRE(iface);
|
||||
CHECK(iface->get_default_config() == json::object());
|
||||
}
|
||||
|
||||
SECTION("overridden -> exactly what the plugin returns")
|
||||
{
|
||||
py::object cap = make_capability("DefaultsCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def get_default_config(self):\n"
|
||||
" return {'speed': 5, 'nested': {'on': True}, 'items': [1, 2]}\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
// Round-trips through py_to_json untouched: the host does not reshape or validate it.
|
||||
CHECK(iface->get_default_config() == json{{"speed", 5}, {"nested", {{"on", true}}}, {"items", {1, 2}}});
|
||||
}
|
||||
|
||||
SECTION("overridden but returns None -> an empty config, never a null")
|
||||
{
|
||||
// `def get_default_config(self): pass` is the easy mistake, and it must not store
|
||||
// "cap_config": null.
|
||||
py::object cap = make_capability("NoneDefaultsCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def get_default_config(self): pass\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
|
||||
const json restored = iface->get_default_config();
|
||||
CHECK(restored == json::object());
|
||||
CHECK_FALSE(restored.is_null());
|
||||
}
|
||||
|
||||
SECTION("overridden but returns a non-object -> an empty config")
|
||||
{
|
||||
py::object cap = make_capability("ScalarDefaultsCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def get_default_config(self): return [1, 2, 3]\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
CHECK(iface->get_default_config() == json::object());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Restoring defaults overwrites only the target capability", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-restore");
|
||||
host_config().load();
|
||||
|
||||
const std::string defaults_body = " def get_name(self): return 'cap'\n"
|
||||
" def get_default_config(self): return {'speed': 1}\n";
|
||||
py::object target = make_capability("RestoreTargetCap", defaults_body, "plugin_a", "cap_a");
|
||||
py::object bystander = make_capability("RestoreBystanderCap", defaults_body, "plugin_b", "cap_a");
|
||||
|
||||
const json edited = json{{"speed", 99}};
|
||||
REQUIRE(py_save_config(target, edited));
|
||||
REQUIRE(py_save_config(bystander, edited));
|
||||
|
||||
// What PluginsDialog::restore_capability_config does: ask the capability, store the answer.
|
||||
auto iface = as_interface(target);
|
||||
REQUIRE(host_config().store_capability_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"), iface->get_default_config()));
|
||||
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"speed", 1}});
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_b"))->config == json{{"speed", 99}});
|
||||
}
|
||||
|
||||
TEST_CASE("A raising get_default_config leaves the stored config untouched", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
ScopedDataDir data_dir_guard("plugin-config-py-restore-raise");
|
||||
host_config().load();
|
||||
|
||||
py::object cap = make_capability("RaisingDefaultsCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def get_default_config(self): raise RuntimeError('boom')\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
REQUIRE(py_save_config(cap, json{{"keep", "me"}}));
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
CHECK_THROWS_AS(iface->get_default_config(), py::error_already_set);
|
||||
|
||||
// The dialog stores nothing when the hook throws: a broken plugin must not wipe user settings.
|
||||
CHECK(host_config().get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"keep", "me"}});
|
||||
}
|
||||
|
||||
TEST_CASE("A raising config UI hook surfaces as an exception the host can catch", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
py::object cap = make_capability("RaisingCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def has_config_ui(self): return True\n"
|
||||
" def get_config_ui(self): raise RuntimeError('boom')\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
|
||||
// The trampoline rethrows; callers catch it and fall back to the default JSON editor.
|
||||
CHECK_THROWS_AS(iface->get_config_ui(), py::error_already_set);
|
||||
|
||||
// Catching it leaves the interpreter usable.
|
||||
CHECK(iface->get_name() == "cap_a");
|
||||
}
|
||||
|
||||
TEST_CASE("A config UI hook returning the wrong type does not crash the host", "[PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system; // declared first: destroyed last
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
py::gil_scoped_acquire gil; // released before plugin_system's destructor shuts Python down
|
||||
|
||||
// has_config_ui() is plugin-authored, so it can return anything; the host must survive the call.
|
||||
py::object cap = make_capability("BadTypeCap",
|
||||
" def get_name(self): return 'cap_a'\n"
|
||||
" def has_config_ui(self): return 'not a bool'\n",
|
||||
"plugin_a", "cap_a");
|
||||
|
||||
auto iface = as_interface(cap);
|
||||
REQUIRE(iface);
|
||||
|
||||
// Deliberately not REQUIRE_THROWS: pybind may coerce or reject the value, and both are fine.
|
||||
// What must hold is that the call is survivable — PluginLoader's guard turns a throw into
|
||||
// "no custom UI".
|
||||
try {
|
||||
(void) iface->has_config_ui();
|
||||
} catch (const std::exception&) {
|
||||
}
|
||||
|
||||
// The capability is still usable afterwards.
|
||||
CHECK(iface->get_name() == "cap_a");
|
||||
CHECK(iface->get_config_ui().empty());
|
||||
}
|
||||
155
tests/slic3rutils/test_plugin_cloud_metadata.cpp
Normal file
155
tests/slic3rutils/test_plugin_cloud_metadata.cpp
Normal file
@@ -0,0 +1,155 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginConfig.hpp>
|
||||
#include <slic3r/plugin/PluginDescriptor.hpp>
|
||||
#include <slic3r/plugin/PluginFsUtils.hpp>
|
||||
#include <slic3r/plugin/PluginManager.hpp>
|
||||
#include <slic3r/plugin/PythonInterpreter.hpp>
|
||||
#include <slic3r/plugin/PythonPluginInterface.hpp>
|
||||
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
// Brings the plugin manager up and shuts both singletons down while boost::log is still alive;
|
||||
// left to their static destructors, shutdown()'s logging runs after boost::log tears down its
|
||||
// thread-local storage and crashes the process on exit (same reason ScopedPluginManager exists in
|
||||
// test_plugin_lifecycle.cpp). initialize() IS needed here: the plugin under test is a
|
||||
// slicing-pipeline script, so discover_plugins() brings up the Python interpreter to parse it,
|
||||
// same as any other plugin.
|
||||
struct ScopedManagerShutdown
|
||||
{
|
||||
bool initialized = PluginManager::instance().initialize();
|
||||
|
||||
~ScopedManagerShutdown()
|
||||
{
|
||||
PluginManager::instance().shutdown();
|
||||
PythonInterpreter::instance().shutdown();
|
||||
}
|
||||
};
|
||||
|
||||
const char* const CLOUD_PLUGIN_SOURCE = R"PY(# /// script
|
||||
# requires-python = ">=3.12"
|
||||
#
|
||||
# [tool.orcaslicer.plugin]
|
||||
# name = "Config Cloud Plugin"
|
||||
# type = "slicing-pipeline"
|
||||
# version = "1.0"
|
||||
# ///
|
||||
print('ok')
|
||||
)PY";
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("plugin latest version uses the authoritative catalog field", "[PluginDescriptor]")
|
||||
{
|
||||
PluginDescriptor descriptor;
|
||||
descriptor.version = "1.3.0";
|
||||
descriptor.latest_version = "1.3.0";
|
||||
PluginChangelog changelog;
|
||||
changelog.version = "1.2.0";
|
||||
descriptor.changelog.push_back(changelog);
|
||||
|
||||
CHECK(descriptor.latest_available_version() == "1.3.0");
|
||||
}
|
||||
|
||||
TEST_CASE("plugin latest version falls back to the descriptor version", "[PluginDescriptor]")
|
||||
{
|
||||
PluginDescriptor descriptor;
|
||||
descriptor.version = "1.1.0";
|
||||
PluginChangelog changelog;
|
||||
changelog.version = "1.0.0";
|
||||
descriptor.changelog.push_back(changelog);
|
||||
|
||||
CHECK(descriptor.latest_available_version() == "1.1.0");
|
||||
}
|
||||
|
||||
// Regression: update_cloud_metadata() replaces a matched entry's descriptor wholesale with the
|
||||
// cloud catalog record (`entry = cloud_entry`). Configuration used to ride on the descriptor, so
|
||||
// that overwrite silently wiped it and plugins fell back to their built-in defaults (found via
|
||||
// Twistify running with its demo defaults instead of the configured values, 2026-07-17).
|
||||
// Configuration now lives in PluginConfig, keyed by the capability identity and kept off the
|
||||
// descriptor entirely, so the merge cannot reach it. This asserts that end to end: a stored
|
||||
// config survives the same refresh path, while the descriptor fields the refresh owns do update.
|
||||
//
|
||||
// The capability need not exist for this to be meaningful: what is pinned is the architectural
|
||||
// invariant that config never rides on the descriptor again. Anyone reintroducing it there, or
|
||||
// adding a cloud-refresh path that prunes config, fails here.
|
||||
TEST_CASE("cloud metadata refresh preserves a plugin's stored config", "[PluginCloudMetadata]")
|
||||
{
|
||||
ScopedManagerShutdown manager_shutdown_guard; // declared first: destroyed last
|
||||
if (!manager_shutdown_guard.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
ScopedDataDir data_dir_guard("cloud-meta-config");
|
||||
|
||||
// A locally-installed cloud plugin: package .py plus an install-state sidecar carrying the
|
||||
// cloud identity. Discovery derives plugin_key from the cloud UUID.
|
||||
const std::string uuid = "11111111-2222-3333-4444-555555555555";
|
||||
const fs::path plugin_dir = fs::path(get_orca_plugins_dir()) / uuid;
|
||||
fs::create_directories(plugin_dir);
|
||||
{
|
||||
std::ofstream out((plugin_dir / "cloud_plugin-test.py").string(), std::ios::binary);
|
||||
out << CLOUD_PLUGIN_SOURCE;
|
||||
}
|
||||
PluginDescriptor sidecar;
|
||||
sidecar.name = "Config Cloud Plugin";
|
||||
sidecar.installed_version = "1.0";
|
||||
sidecar.cloud = CloudPluginState{uuid, true, false, false, false};
|
||||
REQUIRE(write_install_state(plugin_dir, sidecar));
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
const auto find_by_uuid = [&manager, &uuid]() -> PluginDescriptor {
|
||||
for (const PluginDescriptor& d : manager.get_plugin_descriptors(/*include_invalid=*/true))
|
||||
if (d.cloud_uuid() == uuid)
|
||||
return d;
|
||||
return {};
|
||||
};
|
||||
|
||||
const PluginDescriptor discovered = find_by_uuid();
|
||||
REQUIRE(discovered.plugin_key == uuid);
|
||||
REQUIRE(discovered.version == "1.0");
|
||||
|
||||
// The user has configured the plugin's capability (premise).
|
||||
const PluginCapabilityId id{PluginCapabilityType::SlicingPipeline, "Twist", uuid};
|
||||
const json configured{{"twist_deg_per_mm", 1.0}, {"taper_per_mm", 0.0}};
|
||||
REQUIRE(manager.get_config().store_capability_config(id, configured));
|
||||
|
||||
// A cloud catalog refresh for the same plugin: the record knows name/version/uuid and knows
|
||||
// nothing about local config or local paths.
|
||||
PluginDescriptor cloud_record;
|
||||
cloud_record.name = "Config Cloud Plugin";
|
||||
cloud_record.plugin_key = uuid;
|
||||
cloud_record.version = "1.1";
|
||||
cloud_record.cloud = CloudPluginState{uuid, false, false, false, false};
|
||||
manager.update_cloud_metadata({cloud_record});
|
||||
|
||||
// Cloud metadata landed on the descriptor...
|
||||
const PluginDescriptor refreshed = find_by_uuid();
|
||||
CHECK(refreshed.version == "1.1");
|
||||
CHECK(refreshed.plugin_key == uuid);
|
||||
CHECK(refreshed.installed_version == "1.0");
|
||||
|
||||
// ...and the stored config is untouched, both in the live store...
|
||||
const auto stored = manager.get_config().get_config(id);
|
||||
REQUIRE(stored);
|
||||
CHECK(stored->config == configured);
|
||||
|
||||
// ...and on disk, which is what the next run reads back.
|
||||
PluginConfig reloaded;
|
||||
reloaded.load();
|
||||
REQUIRE(reloaded.has_config(id));
|
||||
CHECK(reloaded.get_config(id)->config == configured);
|
||||
}
|
||||
264
tests/slic3rutils/test_plugin_config.cpp
Normal file
264
tests/slic3rutils/test_plugin_config.cpp
Normal file
@@ -0,0 +1,264 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginConfig.hpp>
|
||||
#include <slic3r/plugin/PluginManager.hpp>
|
||||
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
using json = nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
PluginCapabilityId capability_id(PluginCapabilityType type, const char* name, const char* plugin_key)
|
||||
{
|
||||
return {type, name, plugin_key};
|
||||
}
|
||||
|
||||
json read_config_file()
|
||||
{
|
||||
boost::nowide::ifstream ifs(PluginConfig::plugin_config_file().c_str());
|
||||
json root;
|
||||
ifs >> root;
|
||||
return root;
|
||||
}
|
||||
|
||||
void write_config_file(const std::string& contents)
|
||||
{
|
||||
const fs::path path(PluginConfig::plugin_config_file());
|
||||
fs::create_directories(path.parent_path());
|
||||
boost::nowide::ofstream ofs(path.string().c_str(), std::ios::out | std::ios::trunc);
|
||||
ofs << contents;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("PluginConfig creates, reads back and persists a capability config", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-roundtrip");
|
||||
|
||||
PluginConfig config;
|
||||
const PluginCapabilityId id = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a");
|
||||
|
||||
// A capability nobody has configured yet reads as an empty record rather than throwing.
|
||||
CHECK_FALSE(config.has_config(id));
|
||||
CHECK_FALSE(config.get_config(id));
|
||||
|
||||
REQUIRE(config.store_capability_config(id, json{{"speed", 5}}));
|
||||
|
||||
const auto stored = config.get_config(id);
|
||||
REQUIRE(stored);
|
||||
CHECK(stored->id == id);
|
||||
CHECK(stored->config == json{{"speed", 5}});
|
||||
CHECK(config.has_config(id));
|
||||
|
||||
// store_capability_config writes through, so a fresh instance (a restart, in effect) sees it.
|
||||
PluginConfig reloaded;
|
||||
reloaded.load();
|
||||
CHECK(reloaded.get_config(id)->config == json{{"speed", 5}});
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig updates only the target capability's cap_config", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-isolation");
|
||||
|
||||
PluginConfig config;
|
||||
const PluginCapabilityId a_a = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a");
|
||||
const PluginCapabilityId a_b = capability_id(PluginCapabilityType::Script, "cap_b", "plugin_a");
|
||||
const PluginCapabilityId b_a = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_b");
|
||||
// The identity is the full (type, capability, plugin_key) tuple, so all three below are separate records.
|
||||
REQUIRE(config.store_capability_config(a_a, json{{"value", 1}}));
|
||||
REQUIRE(config.store_capability_config(a_b, json{{"value", 2}}));
|
||||
REQUIRE(config.store_capability_config(b_a, json{{"value", 3}}));
|
||||
|
||||
REQUIRE(config.store_capability_config(a_a, json{{"value", 99}}));
|
||||
|
||||
CHECK(config.get_config(a_a)->config == json{{"value", 99}});
|
||||
CHECK(config.get_config(a_b)->config == json{{"value", 2}});
|
||||
CHECK(config.get_config(b_a)->config == json{{"value", 3}});
|
||||
|
||||
// The same holds on disk, not just in memory.
|
||||
PluginConfig reloaded;
|
||||
reloaded.load();
|
||||
CHECK(reloaded.get_config(a_a)->config == json{{"value", 99}});
|
||||
CHECK(reloaded.get_config(a_b)->config == json{{"value", 2}});
|
||||
CHECK(reloaded.get_config(b_a)->config == json{{"value", 3}});
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig isolates same-name capabilities by type", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-type-isolation");
|
||||
const PluginCapabilityId script = capability_id(PluginCapabilityType::Script, "shared", "plugin_a");
|
||||
const PluginCapabilityId importer = capability_id(PluginCapabilityType::Importer, "shared", "plugin_a");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE(config.store_capability_config(script, json{{"value", "script"}}));
|
||||
REQUIRE(config.store_capability_config(importer, json{{"value", "importer"}}));
|
||||
CHECK(config.get_config(script)->config == json{{"value", "script"}});
|
||||
CHECK(config.get_config(importer)->config == json{{"value", "importer"}});
|
||||
|
||||
PluginConfig reloaded;
|
||||
reloaded.load();
|
||||
CHECK(reloaded.get_config(script)->config == json{{"value", "script"}});
|
||||
CHECK(reloaded.get_config(importer)->config == json{{"value", "importer"}});
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig serializes the documented on-disk schema", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-schema");
|
||||
|
||||
PluginConfig config;
|
||||
const PluginCapabilityId id = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a");
|
||||
REQUIRE(config.store_capability_config(id, json{{"speed", 5}}));
|
||||
|
||||
// Locks the field names: an existing config.json must keep loading after any future change.
|
||||
const json root = read_config_file();
|
||||
REQUIRE(root.contains("config"));
|
||||
REQUIRE(root.at("config").is_array());
|
||||
REQUIRE(root.at("config").size() == 1);
|
||||
|
||||
const json& entry = root.at("config").front();
|
||||
CHECK(entry.at("plugin_key") == "plugin_a");
|
||||
CHECK(entry.at("capability") == "cap_a");
|
||||
CHECK(entry.at("capability_type") == "script");
|
||||
CHECK(entry.at("cap_config") == json{{"speed", 5}});
|
||||
CHECK(entry.contains("plugin_version"));
|
||||
// Only cap_config is user data; the rest of the record is host-managed.
|
||||
CHECK(entry.size() == 5);
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig keeps a capability's config after its plugin goes away", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-retention");
|
||||
|
||||
{
|
||||
PluginConfig config;
|
||||
REQUIRE(config.store_capability_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"), json{{"token", "keep me"}}));
|
||||
}
|
||||
|
||||
// config.json is deliberately not keyed to installed plugins: a record outlives its plugin and is
|
||||
// still there on reinstall. Asserts no cleanup path silently drops it.
|
||||
PluginConfig after_removal;
|
||||
after_removal.load();
|
||||
CHECK(after_removal.get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"token", "keep me"}});
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig treats a missing config file as an empty store", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-missing");
|
||||
|
||||
REQUIRE_FALSE(fs::exists(PluginConfig::plugin_config_file()));
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load());
|
||||
CHECK_FALSE(config.has_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a")));
|
||||
CHECK_FALSE(config.dirty());
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig survives a malformed config file", "[PluginConfig]")
|
||||
{
|
||||
SECTION("not JSON at all")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-garbage");
|
||||
write_config_file("this is not json {{{");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load()); // a bad config must not block startup
|
||||
CHECK_FALSE(config.has_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a")));
|
||||
}
|
||||
|
||||
SECTION("valid JSON without the entries array")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-noarray");
|
||||
write_config_file(R"({"config": {"not": "an array"}})");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load());
|
||||
CHECK_FALSE(config.has_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a")));
|
||||
}
|
||||
|
||||
SECTION("entries without an identity are skipped, the rest still load")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-partial");
|
||||
write_config_file(R"({"config": [
|
||||
{"cap_config": {"orphan": true}},
|
||||
{"plugin_key": "plugin_a", "capability": "cap_a", "capability_type": "script", "plugin_version": "1.0.0", "cap_config": {"kept": true}}
|
||||
]})");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load());
|
||||
CHECK(config.get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json{{"kept", true}});
|
||||
CHECK(config.get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->plugin_version == "1.0.0");
|
||||
}
|
||||
|
||||
SECTION("an entry with no cap_config reads as an empty object")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-nocap");
|
||||
write_config_file(R"({"config": [
|
||||
{"plugin_key": "plugin_a", "capability": "cap_a", "capability_type": "script", "plugin_version": "1.0.0"}
|
||||
]})");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load());
|
||||
REQUIRE(config.has_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a")));
|
||||
CHECK(config.get_config(capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a"))->config == json::object());
|
||||
}
|
||||
|
||||
SECTION("legacy entries without capability_type remain addressable")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-notype");
|
||||
write_config_file(R"({"config": [
|
||||
{"plugin_key": "plugin_a", "capability": "cap_a", "plugin_version": "1.0.0", "cap_config": {"old": true}}
|
||||
]})");
|
||||
|
||||
PluginConfig config;
|
||||
REQUIRE_NOTHROW(config.load());
|
||||
const auto id = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a");
|
||||
REQUIRE(config.has_config(id));
|
||||
CHECK(config.get_config(id)->config == json{{"old", true}});
|
||||
|
||||
REQUIRE(config.store_capability_config(id, json{{"migrated", true}}));
|
||||
const json root = read_config_file();
|
||||
REQUIRE(root.at("config").size() == 1);
|
||||
CHECK(root.at("config").front().at("capability_type") == "script");
|
||||
CHECK(root.at("config").front().at("cap_config") == json{{"migrated", true}});
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig refuses to store a record without an identity", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-identity");
|
||||
|
||||
PluginConfig config;
|
||||
config.save_config(CapabilityConfigEntry{capability_id(PluginCapabilityType::Script, "cap_a", ""), "1.0.0", json::object()});
|
||||
config.save_config(CapabilityConfigEntry{capability_id(PluginCapabilityType::Script, "", "plugin_a"), "1.0.0", json::object()});
|
||||
|
||||
// Neither could ever be looked up again, so neither is kept.
|
||||
CHECK_FALSE(config.has_config(capability_id(PluginCapabilityType::Script, "cap_a", "")));
|
||||
CHECK_FALSE(config.has_config(capability_id(PluginCapabilityType::Script, "", "plugin_a")));
|
||||
CHECK_FALSE(config.dirty());
|
||||
}
|
||||
|
||||
TEST_CASE("PluginConfig preserves unknown keys inside cap_config", "[PluginConfig]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("plugin-config-unknown");
|
||||
|
||||
// The host never interprets cap_config, so a nested/odd shape must round-trip untouched.
|
||||
const json nested = json{{"nested", {{"deep", json::array({1, 2, 3})}}}, {"flag", false}, {"name", "x"}};
|
||||
|
||||
PluginConfig config;
|
||||
const PluginCapabilityId id = capability_id(PluginCapabilityType::Script, "cap_a", "plugin_a");
|
||||
REQUIRE(config.store_capability_config(id, nested));
|
||||
|
||||
PluginConfig reloaded;
|
||||
reloaded.load();
|
||||
CHECK(reloaded.get_config(id)->config == nested);
|
||||
}
|
||||
338
tests/slic3rutils/test_plugin_host_api.cpp
Normal file
338
tests/slic3rutils/test_plugin_host_api.cpp
Normal file
@@ -0,0 +1,338 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Model.hpp>
|
||||
#include <libslic3r/PresetBundle.hpp>
|
||||
#include <libslic3r/TriangleMesh.hpp>
|
||||
#include <slic3r/plugin/PythonPluginBridge.hpp>
|
||||
|
||||
#include "python_test_support.hpp"
|
||||
|
||||
#include <pybind11/embed.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
namespace {
|
||||
|
||||
// import_orca_module() lives in python_test_support.hpp (shared with
|
||||
// test_slicing_pipeline_bindings.cpp).
|
||||
|
||||
bool has_attr(const py::handle& object, const char* name)
|
||||
{
|
||||
return py::hasattr(object, name);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Plugin host API exposes host-owned bundle and preset surface to Python", "[PluginHost][Python]")
|
||||
{
|
||||
py::module_ orca = import_orca_module();
|
||||
REQUIRE(has_attr(orca, "host"));
|
||||
|
||||
py::object host = orca.attr("host");
|
||||
REQUIRE(has_attr(host, "PresetBundle"));
|
||||
REQUIRE(has_attr(host, "Preset"));
|
||||
REQUIRE(has_attr(host, "PresetCollection"));
|
||||
REQUIRE(has_attr(host, "Model"));
|
||||
REQUIRE(has_attr(host, "ModelObject"));
|
||||
REQUIRE(has_attr(host, "Plater"));
|
||||
|
||||
py::object preset_bundle_type = host.attr("PresetBundle");
|
||||
CHECK(has_attr(preset_bundle_type, "prints"));
|
||||
CHECK(has_attr(preset_bundle_type, "printers"));
|
||||
CHECK(has_attr(preset_bundle_type, "filaments"));
|
||||
CHECK(has_attr(preset_bundle_type, "current_process_preset"));
|
||||
CHECK(has_attr(preset_bundle_type, "current_printer_preset"));
|
||||
CHECK(has_attr(preset_bundle_type, "current_filament_preset_names"));
|
||||
CHECK(has_attr(preset_bundle_type, "current_filament_presets"));
|
||||
CHECK(has_attr(preset_bundle_type, "full_config_value"));
|
||||
|
||||
py::object preset_collection_type = host.attr("PresetCollection");
|
||||
CHECK(has_attr(preset_collection_type, "get_edited_preset"));
|
||||
CHECK(has_attr(preset_collection_type, "get_selected_preset"));
|
||||
CHECK(has_attr(preset_collection_type, "get_selected_preset_name"));
|
||||
CHECK(has_attr(preset_collection_type, "edited_preset"));
|
||||
CHECK(has_attr(preset_collection_type, "selected_preset"));
|
||||
CHECK(has_attr(preset_collection_type, "selected_preset_name"));
|
||||
|
||||
py::object preset_type = host.attr("Preset");
|
||||
CHECK(has_attr(preset_type, "name"));
|
||||
CHECK(has_attr(preset_type, "type"));
|
||||
CHECK(has_attr(preset_type, "is_default"));
|
||||
CHECK(has_attr(preset_type, "is_system"));
|
||||
CHECK(has_attr(preset_type, "is_user"));
|
||||
CHECK(has_attr(preset_type, "is_from_bundle"));
|
||||
CHECK(has_attr(preset_type, "config_value"));
|
||||
|
||||
Slic3r::PresetBundle bundle;
|
||||
Slic3r::Preset& printer_preset = bundle.printers.get_edited_preset();
|
||||
Slic3r::Preset& process_preset = bundle.prints.get_edited_preset();
|
||||
Slic3r::Preset& filament_preset = bundle.filaments.get_edited_preset();
|
||||
|
||||
printer_preset.config.set("printer_model", "Plugin Host Test Printer", true);
|
||||
bundle.filament_presets = { filament_preset.name, filament_preset.name, "missing filament preset" };
|
||||
|
||||
py::object py_bundle = py::cast(&bundle, py::return_value_policy::reference);
|
||||
|
||||
CHECK(py_bundle.attr("current_printer_preset")().attr("name").cast<std::string>() == printer_preset.name);
|
||||
CHECK(py_bundle.attr("current_print_preset")().attr("name").cast<std::string>() == process_preset.name);
|
||||
CHECK(py_bundle.attr("current_process_preset")().attr("name").cast<std::string>() == process_preset.name);
|
||||
CHECK(py_bundle.attr("current_printer_preset")().attr("is_default").cast<bool>() == printer_preset.is_default);
|
||||
CHECK(py_bundle.attr("current_printer_preset")().attr("is_user")().cast<bool>() == printer_preset.is_user());
|
||||
CHECK(py_bundle.attr("current_printer_preset")().attr("config_value")("printer_model").cast<std::string>() == "Plugin Host Test Printer");
|
||||
CHECK(py_bundle.attr("current_printer_preset")().attr("config_value")("missing_test_key").is_none());
|
||||
|
||||
py::list filament_names = py_bundle.attr("current_filament_preset_names")();
|
||||
REQUIRE(py::len(filament_names) == 3);
|
||||
CHECK(filament_names[0].cast<std::string>() == filament_preset.name);
|
||||
CHECK(filament_names[1].cast<std::string>() == filament_preset.name);
|
||||
CHECK(filament_names[2].cast<std::string>() == "missing filament preset");
|
||||
|
||||
py::list filament_presets = py_bundle.attr("current_filament_presets")();
|
||||
REQUIRE(py::len(filament_presets) == 3);
|
||||
CHECK_FALSE(filament_presets[0].is_none());
|
||||
CHECK(filament_presets[0].attr("name").cast<std::string>() == filament_preset.name);
|
||||
CHECK_FALSE(filament_presets[1].is_none());
|
||||
CHECK(filament_presets[1].attr("name").cast<std::string>() == filament_preset.name);
|
||||
CHECK(filament_presets[2].is_none());
|
||||
|
||||
py::object printers = py_bundle.attr("printers");
|
||||
py::object prints = py_bundle.attr("prints");
|
||||
py::object filaments = py_bundle.attr("filaments");
|
||||
CHECK(printers.attr("get_edited_preset")().attr("name").cast<std::string>() == printer_preset.name);
|
||||
CHECK(prints.attr("get_edited_preset")().attr("name").cast<std::string>() == process_preset.name);
|
||||
CHECK(filaments.attr("get_edited_preset")().attr("name").cast<std::string>() == filament_preset.name);
|
||||
CHECK(printers.attr("get_selected_preset_name")().cast<std::string>() == bundle.printers.get_selected_preset_name());
|
||||
CHECK(printers.attr("get_selected_preset")().attr("name").cast<std::string>() == bundle.printers.get_selected_preset().name);
|
||||
CHECK(printers.attr("selected_preset_name")().cast<std::string>() == bundle.printers.get_selected_preset_name());
|
||||
CHECK(printers.attr("edited_preset")().attr("name").cast<std::string>() == printer_preset.name);
|
||||
CHECK(printers.attr("find_preset")(printer_preset.name).attr("name").cast<std::string>() == printer_preset.name);
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin host API reports unavailable GUI objects before Orca app initialization", "[PluginHost][Python]")
|
||||
{
|
||||
py::object host = import_orca_module().attr("host");
|
||||
|
||||
for (const char* function_name : { "preset_bundle", "plater", "model" }) {
|
||||
CAPTURE(function_name);
|
||||
try {
|
||||
host.attr(function_name)();
|
||||
FAIL("host accessor unexpectedly succeeded without a wx application");
|
||||
} catch (const py::error_already_set& error) {
|
||||
CHECK(error.matches(PyExc_RuntimeError));
|
||||
CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin host API exposes the UI module and guards it before Orca app initialization", "[PluginHost][Python]")
|
||||
{
|
||||
py::object host = import_orca_module().attr("host");
|
||||
REQUIRE(has_attr(host, "ui"));
|
||||
|
||||
py::object ui = host.attr("ui");
|
||||
CHECK(has_attr(ui, "message"));
|
||||
CHECK_FALSE(has_attr(ui, "show_dialog"));
|
||||
CHECK(has_attr(ui, "create_window"));
|
||||
CHECK(has_attr(ui, "WINDOW_MODELESS"));
|
||||
CHECK(has_attr(ui, "WINDOW_MODAL"));
|
||||
CHECK(ui.attr("WINDOW_MODELESS").cast<long>() == 0);
|
||||
CHECK(ui.attr("WINDOW_MODAL").cast<long>() == 1);
|
||||
CHECK(has_attr(ui, "UiWindow"));
|
||||
|
||||
// With no wx application the UI calls marshal to a main thread that does not
|
||||
// exist here; they must fail cleanly with a clear error, not crash.
|
||||
try {
|
||||
ui.attr("message")("hello");
|
||||
FAIL("orca.host.ui.message unexpectedly succeeded without a wx application");
|
||||
} catch (const py::error_already_set& error) {
|
||||
CHECK(error.matches(PyExc_RuntimeError));
|
||||
CHECK(std::string(error.what()).find("OrcaSlicer application is not initialized") != std::string::npos);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin host API exposes model geometry and structure to Python", "[PluginHost][Python]")
|
||||
{
|
||||
using Catch::Matchers::WithinAbs;
|
||||
using Catch::Matchers::WithinRel;
|
||||
|
||||
py::object host = import_orca_module().attr("host");
|
||||
REQUIRE(has_attr(host, "BoundingBox"));
|
||||
REQUIRE(has_attr(host, "Model"));
|
||||
REQUIRE(has_attr(host, "ModelInstance"));
|
||||
REQUIRE(has_attr(host, "ModelVolume"));
|
||||
REQUIRE(has_attr(host, "ModelVolumeType"));
|
||||
|
||||
py::object volume_type_enum = host.attr("ModelVolumeType");
|
||||
CHECK(has_attr(volume_type_enum, "ModelPart"));
|
||||
CHECK(has_attr(volume_type_enum, "ParameterModifier"));
|
||||
CHECK(has_attr(volume_type_enum, "SupportEnforcer"));
|
||||
|
||||
// Build a model in C++: one object with a 10x20x30 mm printable part, a small
|
||||
// modifier volume, and a single instance shifted on the bed.
|
||||
Slic3r::Model model;
|
||||
Slic3r::ModelObject* object = model.add_object();
|
||||
object->name = "Plugin Host Test Cube";
|
||||
|
||||
Slic3r::ModelVolume* part = object->add_volume(Slic3r::make_cube(10.0, 20.0, 30.0));
|
||||
part->name = "cube part";
|
||||
Slic3r::ModelVolume* modifier = object->add_volume(Slic3r::make_cube(2.0, 2.0, 2.0),
|
||||
Slic3r::ModelVolumeType::PARAMETER_MODIFIER);
|
||||
modifier->name = "fit modifier";
|
||||
|
||||
Slic3r::ModelInstance* instance = object->add_instance();
|
||||
instance->set_offset(Slic3r::Vec3d(5.0, 6.0, 0.0));
|
||||
|
||||
py::object py_model = py::cast(&model, py::return_value_policy::reference);
|
||||
|
||||
// Model surface.
|
||||
CHECK(py_model.attr("object_count")().cast<size_t>() == 1);
|
||||
CHECK(py_model.attr("id")().cast<size_t>() == model.id().id);
|
||||
CHECK(py_model.attr("bounding_box")().attr("defined").cast<bool>());
|
||||
|
||||
// Object surface.
|
||||
py::object py_object = py_model.attr("object")(0);
|
||||
CHECK(py_object.attr("name").cast<std::string>() == "Plugin Host Test Cube");
|
||||
CHECK(py_object.attr("id")().cast<size_t>() == object->id().id);
|
||||
CHECK(py_object.attr("instance_count")().cast<size_t>() == 1);
|
||||
CHECK(py_object.attr("volume_count")().cast<size_t>() == 2);
|
||||
CHECK(py::len(py_object.attr("instances")()) == 1);
|
||||
CHECK(py::len(py_object.attr("volumes")()) == 2);
|
||||
CHECK(py_object.attr("is_multiparts")().cast<bool>());
|
||||
|
||||
// Intrinsic (untransformed) object size must match the printable part's dimensions.
|
||||
py::object obj_size = py_object.attr("raw_mesh_bounding_box")().attr("size");
|
||||
REQUIRE_THAT(obj_size[py::int_(0)].cast<double>(), WithinAbs(10.0, 1e-3));
|
||||
REQUIRE_THAT(obj_size[py::int_(1)].cast<double>(), WithinAbs(20.0, 1e-3));
|
||||
REQUIRE_THAT(obj_size[py::int_(2)].cast<double>(), WithinAbs(30.0, 1e-3));
|
||||
|
||||
// Instance surface.
|
||||
py::object py_instance = py_object.attr("instance")(0);
|
||||
py::object inst_offset = py_instance.attr("offset")();
|
||||
REQUIRE_THAT(inst_offset[py::int_(0)].cast<double>(), WithinAbs(5.0, 1e-6));
|
||||
REQUIRE_THAT(inst_offset[py::int_(1)].cast<double>(), WithinAbs(6.0, 1e-6));
|
||||
REQUIRE_THAT(inst_offset[py::int_(2)].cast<double>(), WithinAbs(0.0, 1e-6));
|
||||
CHECK(py_instance.attr("id")().cast<size_t>() == instance->id().id);
|
||||
|
||||
// Volume surface — part.
|
||||
py::object py_part = py_object.attr("volume")(0);
|
||||
CHECK(py_part.attr("name").cast<std::string>() == "cube part");
|
||||
CHECK(py_part.attr("is_model_part")().cast<bool>());
|
||||
CHECK_FALSE(py_part.attr("is_modifier")().cast<bool>());
|
||||
CHECK(py_part.attr("type")().cast<Slic3r::ModelVolumeType>() == Slic3r::ModelVolumeType::MODEL_PART);
|
||||
CHECK(py_part.attr("facets_count")().cast<size_t>() == 12);
|
||||
REQUIRE_THAT(py_part.attr("volume")().cast<double>(), WithinRel(6000.0, 1e-2));
|
||||
|
||||
// Volume surface — modifier.
|
||||
py::object py_modifier = py_object.attr("volume")(1);
|
||||
CHECK(py_modifier.attr("is_modifier")().cast<bool>());
|
||||
CHECK_FALSE(py_modifier.attr("is_model_part")().cast<bool>());
|
||||
CHECK(py_modifier.attr("type")().cast<Slic3r::ModelVolumeType>() == Slic3r::ModelVolumeType::PARAMETER_MODIFIER);
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin host API exposes TriangleMesh geometry to Python", "[PluginHost][Python]")
|
||||
{
|
||||
using Catch::Matchers::WithinAbs;
|
||||
using Catch::Matchers::WithinRel;
|
||||
|
||||
py::object host = import_orca_module().attr("host");
|
||||
REQUIRE(has_attr(host, "TriangleMesh"));
|
||||
|
||||
py::object mesh_type = host.attr("TriangleMesh");
|
||||
for (const char* member : { "vertex_count", "triangle_count", "facets_count", "is_empty",
|
||||
"vertices", "triangles", "face_normals", "vertex", "triangle",
|
||||
"volume", "bounding_box", "is_manifold" }) {
|
||||
CAPTURE(member);
|
||||
CHECK(has_attr(mesh_type, member));
|
||||
}
|
||||
|
||||
// A 10 x 20 x 30 mm box: 8 vertices, 12 triangles.
|
||||
Slic3r::Model model;
|
||||
Slic3r::ModelObject* object = model.add_object();
|
||||
object->add_volume(Slic3r::make_cube(10.0, 20.0, 30.0));
|
||||
Slic3r::ModelInstance* instance = object->add_instance();
|
||||
instance->set_offset(Slic3r::Vec3d(5.0, 6.0, 0.0));
|
||||
|
||||
py::object py_object = py::cast(object, py::return_value_policy::reference);
|
||||
py::object py_volume = py_object.attr("volume")(0);
|
||||
py::object mesh = py_volume.attr("mesh")();
|
||||
|
||||
// Deterministic, numpy-free surface.
|
||||
CHECK(mesh.attr("vertex_count")().cast<size_t>() == 8);
|
||||
CHECK(mesh.attr("triangle_count")().cast<size_t>() == 12);
|
||||
CHECK(mesh.attr("facets_count")().cast<size_t>() == 12);
|
||||
CHECK_FALSE(mesh.attr("is_empty")().cast<bool>());
|
||||
CHECK(mesh.attr("is_manifold")().cast<bool>());
|
||||
REQUIRE_THAT(mesh.attr("volume")().cast<double>(), WithinRel(6000.0, 1e-2));
|
||||
|
||||
py::object bbox_size = mesh.attr("bounding_box")().attr("size");
|
||||
REQUIRE_THAT(bbox_size[py::int_(0)].cast<double>(), WithinAbs(10.0, 1e-3));
|
||||
REQUIRE_THAT(bbox_size[py::int_(1)].cast<double>(), WithinAbs(20.0, 1e-3));
|
||||
REQUIRE_THAT(bbox_size[py::int_(2)].cast<double>(), WithinAbs(30.0, 1e-3));
|
||||
|
||||
py::object vertex0 = mesh.attr("vertex")(0);
|
||||
REQUIRE(py::len(vertex0) == 3);
|
||||
py::object triangle0 = mesh.attr("triangle")(0);
|
||||
REQUIRE(py::len(triangle0) == 3);
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
int idx = triangle0[py::int_(k)].cast<int>();
|
||||
CHECK(idx >= 0);
|
||||
CHECK(idx < 8);
|
||||
}
|
||||
CHECK_THROWS_AS(mesh.attr("vertex")(8), py::error_already_set);
|
||||
CHECK_THROWS_AS(mesh.attr("triangle")(12), py::error_already_set);
|
||||
|
||||
// numpy path: exercised when numpy is importable, otherwise assert the clear
|
||||
// "numpy required" error so the absent path is itself covered.
|
||||
bool have_numpy = false;
|
||||
try {
|
||||
py::module_::import("numpy");
|
||||
have_numpy = true;
|
||||
} catch (const py::error_already_set&) {
|
||||
have_numpy = false;
|
||||
}
|
||||
|
||||
if (!have_numpy) {
|
||||
WARN("numpy unavailable in unit-test interpreter; asserting the numpy-absent error path");
|
||||
try {
|
||||
mesh.attr("vertices")();
|
||||
FAIL("vertices() must raise ImportError when numpy is unavailable");
|
||||
} catch (const py::error_already_set& error) {
|
||||
CHECK(error.matches(PyExc_ImportError));
|
||||
CHECK(std::string(error.what()).find("numpy is required") != std::string::npos);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
py::object vertices = mesh.attr("vertices")();
|
||||
CHECK(vertices.attr("shape").cast<py::tuple>()[py::int_(0)].cast<size_t>() == 8);
|
||||
CHECK(vertices.attr("shape").cast<py::tuple>()[py::int_(1)].cast<size_t>() == 3);
|
||||
CHECK(vertices.attr("dtype").attr("name").cast<std::string>() == "float32");
|
||||
CHECK_FALSE(vertices.attr("flags").attr("writeable").cast<bool>());
|
||||
CHECK_FALSE(vertices.attr("base").is_none()); // zero-copy view keeps an owner alive
|
||||
CHECK_THROWS_AS(vertices.attr("__setitem__")(py::make_tuple(0, 0), py::float_(1.0)), py::error_already_set);
|
||||
|
||||
py::object triangles = mesh.attr("triangles")();
|
||||
CHECK(triangles.attr("shape").cast<py::tuple>()[py::int_(0)].cast<size_t>() == 12);
|
||||
CHECK(triangles.attr("shape").cast<py::tuple>()[py::int_(1)].cast<size_t>() == 3);
|
||||
CHECK(triangles.attr("dtype").attr("name").cast<std::string>() == "int32");
|
||||
CHECK_FALSE(triangles.attr("flags").attr("writeable").cast<bool>());
|
||||
|
||||
py::object face_normals = mesh.attr("face_normals")();
|
||||
CHECK(face_normals.attr("shape").cast<py::tuple>()[py::int_(0)].cast<size_t>() == 12);
|
||||
CHECK(face_normals.attr("dtype").attr("name").cast<std::string>() == "float32");
|
||||
|
||||
// World-space transform matrices.
|
||||
py::object volume_matrix = py_volume.attr("matrix")();
|
||||
CHECK(volume_matrix.attr("shape").cast<py::tuple>()[py::int_(0)].cast<size_t>() == 4);
|
||||
CHECK(volume_matrix.attr("shape").cast<py::tuple>()[py::int_(1)].cast<size_t>() == 4);
|
||||
CHECK(volume_matrix.attr("dtype").attr("name").cast<std::string>() == "float64");
|
||||
|
||||
py::object instance_matrix = py_object.attr("instance")(0).attr("matrix")();
|
||||
CHECK(instance_matrix.attr("shape").cast<py::tuple>()[py::int_(0)].cast<size_t>() == 4);
|
||||
// Instance offset (5, 6, 0) must land in the matrix translation column.
|
||||
REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(0, 3)).cast<double>(), WithinAbs(5.0, 1e-6));
|
||||
REQUIRE_THAT(instance_matrix.attr("__getitem__")(py::make_tuple(1, 3)).cast<double>(), WithinAbs(6.0, 1e-6));
|
||||
}
|
||||
123
tests/slic3rutils/test_plugin_install.cpp
Normal file
123
tests/slic3rutils/test_plugin_install.cpp
Normal file
@@ -0,0 +1,123 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginLoader.hpp>
|
||||
#include <slic3r/plugin/PluginDescriptor.hpp>
|
||||
#include <slic3r/plugin/PluginFsUtils.hpp>
|
||||
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
namespace {
|
||||
|
||||
fs::path write_py_file(const fs::path& dir, const std::string& filename, const std::string& contents)
|
||||
{
|
||||
fs::create_directories(dir);
|
||||
const fs::path p = dir / filename;
|
||||
std::ofstream out(p.string(), std::ios::binary);
|
||||
out << contents;
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("install_plugin rejects a cloud UUID containing path traversal", "[PluginInstall]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("cor2");
|
||||
|
||||
// Package contents are irrelevant: the UUID is validated before metadata is read.
|
||||
const fs::path py = write_py_file(data_dir_guard.dir / "src", "evil.py", "print('hi')\n");
|
||||
|
||||
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
// is_cloud_plugin() -> true; cloud_uuid() -> the traversal string.
|
||||
descriptor.cloud = CloudPluginState{"../../escape", true, false, false, false};
|
||||
|
||||
std::string error;
|
||||
const bool installed = plugin_loader::install_plugin(py, /*cloud_user_id=*/"test-user", descriptor, error);
|
||||
|
||||
REQUIRE_FALSE(installed);
|
||||
CHECK_THAT(error, Catch::Matchers::ContainsSubstring("valid identifier"));
|
||||
}
|
||||
|
||||
TEST_CASE("install_plugin rejects a side-loaded .py with no PEP 723 metadata", "[PluginInstall]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("cor3-bad");
|
||||
|
||||
// No `# /// script` block -> name stays empty and type stays Unknown.
|
||||
const fs::path py = write_py_file(data_dir_guard.dir / "src", "nameless.py", "print('no metadata here')\n");
|
||||
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
std::string error;
|
||||
const bool installed = plugin_loader::install_plugin(py, /*cloud_user_id=*/"", descriptor, error);
|
||||
|
||||
REQUIRE_FALSE(installed);
|
||||
CHECK_THAT(error, Catch::Matchers::ContainsSubstring("PEP 723"));
|
||||
}
|
||||
|
||||
TEST_CASE("install_plugin accepts a side-loaded .py with complete PEP 723 metadata", "[PluginInstall]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("cor3-good");
|
||||
|
||||
const std::string contents =
|
||||
"# /// script\n"
|
||||
"# requires-python = \">=3.12\"\n"
|
||||
"#\n"
|
||||
"# [tool.orcaslicer.plugin]\n"
|
||||
"# name = \"Test Plugin\"\n"
|
||||
"# type = \"script\"\n"
|
||||
"# ///\n"
|
||||
"print('ok')\n";
|
||||
const fs::path py = write_py_file(data_dir_guard.dir / "src", "good.py", contents);
|
||||
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
std::string error;
|
||||
const bool installed = plugin_loader::install_plugin(py, /*cloud_user_id=*/"", descriptor, error);
|
||||
|
||||
// Positive control: a complete side-loaded .py must still install (guards against over-rejection).
|
||||
REQUIRE(installed);
|
||||
CHECK(error.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's installed version", "[PluginInstall]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("installed-version");
|
||||
|
||||
const fs::path plugin_dir = data_dir_guard.dir / "plugin";
|
||||
fs::create_directories(plugin_dir);
|
||||
|
||||
// A cloud plugin whose local manifest/PEP723 header lags the version actually fetched from
|
||||
// the cloud: the user bumped the version on the cloud without touching the local header.
|
||||
PluginDescriptor descriptor;
|
||||
descriptor.name = "Versioned Plugin";
|
||||
descriptor.version = "1.0.0"; // stale header version
|
||||
descriptor.installed_version = "1.2.0"; // version fetched from the cloud at install time
|
||||
descriptor.cloud = CloudPluginState{"uuid-1", true, false, false, false};
|
||||
|
||||
REQUIRE(write_install_state(plugin_dir, descriptor));
|
||||
|
||||
// The writer must persist the installed_version (1.2.0), not the header version (1.0.0),
|
||||
// so a subsequent re-write from a freshly-scanned descriptor cannot clobber it.
|
||||
PluginInstallState state;
|
||||
REQUIRE(read_install_state(plugin_dir, state));
|
||||
CHECK(state.installed_version == "1.2.0");
|
||||
|
||||
// Reading the sidecar back onto a freshly-scanned descriptor (whose header version is still
|
||||
// 1.0.0) must surface the cloud-installed 1.2.0. This is what lets update_cloud_metadata compare
|
||||
// the cloud's latest version against the installed version instead of the stale header, so an
|
||||
// already-updated plugin no longer looks perpetually out of date.
|
||||
PluginDescriptor scanned;
|
||||
scanned.version = "1.0.0"; // as parsed from the unchanged PEP723 header
|
||||
read_install_state(plugin_dir, scanned);
|
||||
CHECK(scanned.installed_version == "1.2.0");
|
||||
}
|
||||
758
tests/slic3rutils/test_plugin_lifecycle.cpp
Normal file
758
tests/slic3rutils/test_plugin_lifecycle.cpp
Normal file
@@ -0,0 +1,758 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginDescriptor.hpp>
|
||||
#include <slic3r/plugin/PluginManager.hpp>
|
||||
#include <slic3r/plugin/PluginFsUtils.hpp>
|
||||
#include <slic3r/plugin/PythonInterpreter.hpp>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using namespace Slic3r;
|
||||
namespace fs = boost::filesystem;
|
||||
|
||||
// Plugin load/unload lifecycle: discovery -> load -> capability materialization -> enable/disable
|
||||
// -> unload.
|
||||
//
|
||||
// Each Catch2 test case runs in its own process (catch_discover_tests), so the PluginManager and
|
||||
// interpreter singletons are brought up at most once per test.
|
||||
|
||||
namespace {
|
||||
|
||||
// Point data_dir() at a throwaway directory for the lifetime of a test and restore the previous
|
||||
// value afterwards, so discovery scans a disposable {data_dir}/orca_plugins tree and tests don't
|
||||
// leak state into each other.
|
||||
struct ScopedDataDir
|
||||
{
|
||||
std::string previous;
|
||||
fs::path dir;
|
||||
|
||||
explicit ScopedDataDir(const std::string& tag)
|
||||
{
|
||||
previous = data_dir();
|
||||
dir = fs::temp_directory_path() / fs::unique_path("orca-" + tag + "-%%%%-%%%%");
|
||||
fs::create_directories(dir);
|
||||
set_data_dir(dir.string());
|
||||
}
|
||||
|
||||
~ScopedDataDir()
|
||||
{
|
||||
set_data_dir(previous);
|
||||
boost::system::error_code ec;
|
||||
fs::remove_all(dir, ec);
|
||||
}
|
||||
|
||||
fs::path plugins_dir() const { return dir / "orca_plugins"; }
|
||||
};
|
||||
|
||||
// Brings the plugin system up, and tears it down explicitly at the end of the test.
|
||||
//
|
||||
// Shutting the interpreter down here, rather than leaving it to PythonInterpreter's static
|
||||
// destructor, mirrors what the app does (GUI_App finalizes it before exit). Left to static
|
||||
// destruction, shutdown()'s logging runs after boost::log has torn down its thread-local storage
|
||||
// and throws, aborting the process after the tests have already passed.
|
||||
//
|
||||
// Declare this FIRST in a test so it is destroyed last.
|
||||
struct ScopedPluginManager
|
||||
{
|
||||
bool initialized = false;
|
||||
|
||||
ScopedPluginManager() { initialized = PluginManager::instance().initialize(); }
|
||||
~ScopedPluginManager()
|
||||
{
|
||||
PluginManager::instance().shutdown();
|
||||
PythonInterpreter::instance().shutdown();
|
||||
}
|
||||
};
|
||||
|
||||
// A minimal script plugin exposing exactly one capability, "Echo".
|
||||
const char* const ECHO_PLUGIN_SOURCE = R"PY(# /// script
|
||||
# requires-python = ">=3.12"
|
||||
#
|
||||
# [tool.orcaslicer.plugin]
|
||||
# name = "Echo Plugin"
|
||||
# description = "Plugin lifecycle characterization fixture"
|
||||
# author = "OrcaSlicer"
|
||||
# version = "1.0"
|
||||
# type = "script"
|
||||
# ///
|
||||
import orca
|
||||
|
||||
class Echo(orca.script.ScriptPluginCapabilityBase):
|
||||
def get_name(self):
|
||||
return "Echo"
|
||||
|
||||
def execute(self, ctx):
|
||||
return orca.ExecutionResult.success()
|
||||
|
||||
@orca.plugin
|
||||
class EchoPackage(orca.base):
|
||||
def register_capabilities(self):
|
||||
orca.register_capability(Echo)
|
||||
)PY";
|
||||
|
||||
// Writes {data_dir}/orca_plugins/<stem>/<stem>.py and returns the plugin directory.
|
||||
fs::path write_plugin(const ScopedDataDir& data_dir_guard, const std::string& stem, const std::string& source)
|
||||
{
|
||||
const fs::path plugin_dir = data_dir_guard.plugins_dir() / stem;
|
||||
fs::create_directories(plugin_dir);
|
||||
|
||||
std::ofstream out((plugin_dir / (stem + ".py")).string(), std::ios::binary);
|
||||
out << source;
|
||||
out.close();
|
||||
|
||||
return plugin_dir;
|
||||
}
|
||||
|
||||
// Loads a plugin and blocks until the detached worker thread is done with it.
|
||||
bool load_and_wait(PluginManager& manager,
|
||||
const std::string& plugin_key,
|
||||
std::string& error,
|
||||
std::vector<std::string> capabilities_to_enable = {})
|
||||
{
|
||||
manager.load_plugin(plugin_key, /*skip_deps=*/true, std::move(capabilities_to_enable));
|
||||
return manager.wait_for_plugin_load(plugin_key, std::chrono::seconds(120), error);
|
||||
}
|
||||
|
||||
std::shared_ptr<PluginCapabilityInterface> find_capability(PluginManager& manager, const std::string& plugin_key,
|
||||
const std::string& name)
|
||||
{ return manager.get_plugin_capability({PluginCapabilityType::Unknown, name, plugin_key}, /*only_enabled=*/false); }
|
||||
|
||||
std::vector<std::shared_ptr<PluginCapabilityInterface>> capabilities_of(PluginManager& manager, const std::string& plugin_key)
|
||||
{
|
||||
return manager.get_plugin_capabilities(plugin_key, PluginCapabilityType::Unknown, /*only_enabled=*/false);
|
||||
}
|
||||
|
||||
PluginDescriptor descriptor_of(PluginManager& manager, const std::string& plugin_key)
|
||||
{
|
||||
PluginDescriptor descriptor;
|
||||
manager.try_get_plugin_descriptor(plugin_key, descriptor);
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("A discovered script plugin loads and materializes its capability", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-load");
|
||||
write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
REQUIRE(manager.try_get_valid_plugin_descriptor("Echo_Plugin", descriptor));
|
||||
CHECK(descriptor.name == "Echo Plugin");
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
INFO("load error: " << error);
|
||||
CHECK(error.empty());
|
||||
|
||||
CHECK(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
CHECK(manager.get_plugin_load_error("Echo_Plugin").empty());
|
||||
|
||||
const auto capabilities = capabilities_of(manager, "Echo_Plugin");
|
||||
REQUIRE(capabilities.size() == 1);
|
||||
|
||||
const auto& echo = capabilities.front();
|
||||
CHECK(echo->name() == "Echo");
|
||||
CHECK(echo->type() == PluginCapabilityType::Script);
|
||||
CHECK(echo->is_enabled());
|
||||
CHECK(echo->audit_plugin_key() == "Echo_Plugin");
|
||||
|
||||
CHECK(manager.get_plugin_capability({PluginCapabilityType::Script, "Echo", "Echo_Plugin"}) == echo);
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("Plugin manager can initialize again after shutdown", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-reinitialize");
|
||||
write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
manager.shutdown();
|
||||
|
||||
REQUIRE(manager.initialize());
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
CHECK(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("Duplicate discovered plugin keys are reported", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-duplicate-key");
|
||||
for (const char* directory_name : {"first", "second"}) {
|
||||
const fs::path plugin_dir = data_dir_guard.plugins_dir() / directory_name;
|
||||
fs::create_directories(plugin_dir);
|
||||
std::ofstream out((plugin_dir / "Shared.py").string(), std::ios::binary);
|
||||
out << ECHO_PLUGIN_SOURCE;
|
||||
}
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
PluginDescriptor descriptor;
|
||||
REQUIRE(manager.try_get_plugin_descriptor("Shared", descriptor));
|
||||
CHECK(descriptor.has_error());
|
||||
CHECK(descriptor.normalized_error().find("Duplicate plugin key") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_CASE("Unloading a plugin drops the package and its capabilities", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-unload");
|
||||
write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
REQUIRE(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
|
||||
CHECK(manager.unload_plugin("Echo_Plugin"));
|
||||
|
||||
CHECK_FALSE(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
CHECK(manager.get_plugin_capabilities("Echo_Plugin").empty());
|
||||
CHECK(manager.get_plugin_capability({PluginCapabilityType::Script, "Echo", "Echo_Plugin"}) == nullptr);
|
||||
|
||||
// The package stays discovered, but nothing capability-shaped survives the unload.
|
||||
const PluginDescriptor descriptor = descriptor_of(manager, "Echo_Plugin");
|
||||
CHECK(descriptor.plugin_key == "Echo_Plugin");
|
||||
CHECK(capabilities_of(manager, "Echo_Plugin").empty());
|
||||
}
|
||||
|
||||
TEST_CASE("Python module release removes package submodules and owned sys.path", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("module-release");
|
||||
const fs::path package_root = data_dir_guard.dir / "reload_package";
|
||||
fs::create_directories(package_root);
|
||||
|
||||
auto write_package = [&](const std::string& value) {
|
||||
std::ofstream init((package_root / "__init__.py").string());
|
||||
init << "import reload_helper\nfrom . import sub\nVALUE = sub.VALUE\n";
|
||||
std::ofstream sub((package_root / "sub.py").string());
|
||||
sub << "VALUE = " << value << "\n";
|
||||
std::ofstream helper((package_root.parent_path() / "reload_helper.py").string());
|
||||
helper << "VALUE = 'helper'\n";
|
||||
};
|
||||
|
||||
write_package("'old'");
|
||||
|
||||
PythonInterpreter& interpreter = PythonInterpreter::instance();
|
||||
std::vector<std::string> paths;
|
||||
std::vector<std::string> modules;
|
||||
std::string error;
|
||||
PyObject* module = interpreter.load_module_from_directory(
|
||||
package_root.parent_path().string(), "reload_package", error, &paths, &modules);
|
||||
REQUIRE(module != nullptr);
|
||||
INFO("module load error: " << error);
|
||||
REQUIRE(error.empty());
|
||||
REQUIRE(paths.size() == 1);
|
||||
|
||||
{
|
||||
PythonGILState gil;
|
||||
REQUIRE(gil);
|
||||
PyObject* modules = PyImport_GetModuleDict();
|
||||
REQUIRE(modules != nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_package") != nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_package.sub") != nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_helper") != nullptr);
|
||||
}
|
||||
|
||||
Plugin loaded;
|
||||
loaded.module = module;
|
||||
loaded.module_name = "reload_package";
|
||||
loaded.plugin_sys_paths = paths;
|
||||
loaded.plugin_modules = modules;
|
||||
loaded.release_module();
|
||||
|
||||
{
|
||||
PythonGILState gil;
|
||||
REQUIRE(gil);
|
||||
PyObject* modules = PyImport_GetModuleDict();
|
||||
REQUIRE(modules != nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_package") == nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_package.sub") == nullptr);
|
||||
CHECK(PyDict_GetItemString(modules, "reload_helper") == nullptr);
|
||||
|
||||
PyObject* sys_path = PySys_GetObject("path");
|
||||
REQUIRE(sys_path != nullptr);
|
||||
PyObjectPtr path(PyUnicode_DecodeFSDefault(paths.front().c_str()));
|
||||
REQUIRE(path);
|
||||
CHECK(PySequence_Contains(sys_path, path.get()) == 0);
|
||||
}
|
||||
|
||||
// Ensure the next import executes the new submodule rather than reusing a stale package child.
|
||||
write_package("'new'");
|
||||
boost::system::error_code ec;
|
||||
fs::remove_all(package_root / "__pycache__", ec);
|
||||
|
||||
paths.clear();
|
||||
modules.clear();
|
||||
module = interpreter.load_module_from_directory(
|
||||
package_root.parent_path().string(), "reload_package", error, &paths, &modules);
|
||||
REQUIRE(module != nullptr);
|
||||
REQUIRE(error.empty());
|
||||
|
||||
{
|
||||
PythonGILState gil;
|
||||
REQUIRE(gil);
|
||||
PyObjectPtr value(PyObject_GetAttrString(module, "VALUE"));
|
||||
REQUIRE(value);
|
||||
CHECK(std::string(PyUnicode_AsUTF8(value.get())) == "new");
|
||||
}
|
||||
|
||||
loaded.module = module;
|
||||
loaded.module_name = "reload_package";
|
||||
loaded.plugin_sys_paths = paths;
|
||||
loaded.plugin_modules = modules;
|
||||
loaded.release_module();
|
||||
}
|
||||
|
||||
TEST_CASE("A capability disabled in the sidecar loads disabled", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-disabled");
|
||||
const fs::path plugin_dir = write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
// Pre-seed the sidecar with the capability disabled, as a previous session would have.
|
||||
PluginInstallState state;
|
||||
state.installed_from = "local";
|
||||
state.installed_version = "1.0";
|
||||
state.plugin_name = "Echo Plugin";
|
||||
state.enabled = true;
|
||||
state.capabilities = {{"Echo", false}};
|
||||
REQUIRE(write_install_state(plugin_dir, state));
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
REQUIRE(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
|
||||
// The capability still materializes — it is loaded, but logically disabled, so consumers skip it.
|
||||
const auto echo = find_capability(manager, "Echo_Plugin", "Echo");
|
||||
REQUIRE(echo != nullptr);
|
||||
CHECK_FALSE(echo->is_enabled());
|
||||
|
||||
CHECK(manager.get_plugin_capabilities("Echo_Plugin", PluginCapabilityType::Unknown, /*only_enabled=*/true).empty());
|
||||
CHECK(manager.get_plugin_capabilities("Echo_Plugin", PluginCapabilityType::Unknown, /*only_enabled=*/false).size() == 1);
|
||||
|
||||
// An empty load request must preserve the persisted disabled state even when the package is
|
||||
// already loaded.
|
||||
std::string no_request_error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", no_request_error));
|
||||
CHECK_FALSE(find_capability(manager, "Echo_Plugin", "Echo")->is_enabled());
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("Disabling a capability round-trips through the sidecar and survives a reload", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-roundtrip");
|
||||
const fs::path plugin_dir = write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
REQUIRE(find_capability(manager, "Echo_Plugin", "Echo")->is_enabled());
|
||||
|
||||
// Disabling writes the choice through to .install_state.json.
|
||||
manager.set_capability_enabled({PluginCapabilityType::Unknown, "Echo", "Echo_Plugin"}, false);
|
||||
CHECK_FALSE(find_capability(manager, "Echo_Plugin", "Echo")->is_enabled());
|
||||
|
||||
PluginInstallState persisted;
|
||||
REQUIRE(read_install_state(plugin_dir, persisted));
|
||||
REQUIRE(persisted.capabilities.size() == 1);
|
||||
CHECK(persisted.capabilities.front().first == "Echo");
|
||||
CHECK_FALSE(persisted.capabilities.front().second);
|
||||
|
||||
// Unload and reload: the user's choice must survive.
|
||||
REQUIRE(manager.unload_plugin("Echo_Plugin"));
|
||||
|
||||
std::string reload_error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", reload_error));
|
||||
|
||||
const auto echo = find_capability(manager, "Echo_Plugin", "Echo");
|
||||
REQUIRE(echo != nullptr);
|
||||
CHECK_FALSE(echo->is_enabled());
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("A capability disabled after load stays disabled when rediscovered and reloaded", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-reload-live");
|
||||
write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
|
||||
manager.set_capability_enabled({PluginCapabilityType::Unknown, "Echo", "Echo_Plugin"}, false);
|
||||
REQUIRE(manager.unload_plugin("Echo_Plugin"));
|
||||
|
||||
// Rediscover, as the app does when a plugin is toggled off and back on. The enable flags the
|
||||
// loader seeds from must come from the sidecar just written, not from a stale cache.
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/false);
|
||||
|
||||
std::string reload_error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", reload_error));
|
||||
|
||||
const auto echo = find_capability(manager, "Echo_Plugin", "Echo");
|
||||
REQUIRE(echo != nullptr);
|
||||
CHECK_FALSE(echo->is_enabled());
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("Re-enabling a disabled capability writes the sidecar back", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-reenable");
|
||||
const fs::path plugin_dir = write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginInstallState state;
|
||||
state.installed_from = "local";
|
||||
state.plugin_name = "Echo Plugin";
|
||||
state.enabled = true;
|
||||
state.capabilities = {{"Echo", false}};
|
||||
REQUIRE(write_install_state(plugin_dir, state));
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
|
||||
// An explicit request overrides the persisted disabled state, including on a fresh load.
|
||||
REQUIRE(manager.unload_plugin("Echo_Plugin"));
|
||||
std::string enable_error;
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", enable_error, {"Echo"}));
|
||||
|
||||
const auto echo = find_capability(manager, "Echo_Plugin", "Echo");
|
||||
REQUIRE(echo != nullptr);
|
||||
CHECK(echo->is_enabled());
|
||||
|
||||
PluginInstallState persisted;
|
||||
REQUIRE(read_install_state(plugin_dir, persisted));
|
||||
REQUIRE(persisted.capabilities.size() == 1);
|
||||
CHECK(persisted.capabilities.front().first == "Echo");
|
||||
CHECK(persisted.capabilities.front().second);
|
||||
|
||||
manager.unload_plugin("Echo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("Overwriting a local plugin unloads its live module", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-overwrite");
|
||||
const fs::path package_dir = data_dir_guard.dir / "packages";
|
||||
fs::create_directories(package_dir);
|
||||
const fs::path package = package_dir / "Echo_Plugin.py";
|
||||
{
|
||||
std::ofstream out(package.string(), std::ios::binary);
|
||||
out << ECHO_PLUGIN_SOURCE;
|
||||
}
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
std::string error;
|
||||
REQUIRE(manager.install_plugin(package, error));
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
REQUIRE(load_and_wait(manager, "Echo_Plugin", error));
|
||||
REQUIRE(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
|
||||
REQUIRE(manager.install_plugin(package, error));
|
||||
CHECK_FALSE(manager.is_plugin_loaded("Echo_Plugin"));
|
||||
}
|
||||
|
||||
TEST_CASE("capabilities_to_enable selects which capabilities come up enabled", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
// Two capabilities in one package; only the second is requested.
|
||||
const char* const two_cap_source = R"PY(# /// script
|
||||
# requires-python = ">=3.12"
|
||||
#
|
||||
# [tool.orcaslicer.plugin]
|
||||
# name = "Duo Plugin"
|
||||
# version = "1.0"
|
||||
# type = "script"
|
||||
# ///
|
||||
import orca
|
||||
|
||||
class Alpha(orca.script.ScriptPluginCapabilityBase):
|
||||
def get_name(self):
|
||||
return "Alpha"
|
||||
|
||||
def execute(self, ctx):
|
||||
return orca.ExecutionResult.success()
|
||||
|
||||
class Beta(orca.script.ScriptPluginCapabilityBase):
|
||||
def get_name(self):
|
||||
return "Beta"
|
||||
|
||||
def execute(self, ctx):
|
||||
return orca.ExecutionResult.success()
|
||||
|
||||
@orca.plugin
|
||||
class DuoPackage(orca.base):
|
||||
def register_capabilities(self):
|
||||
orca.register_capability(Alpha)
|
||||
orca.register_capability(Beta)
|
||||
)PY";
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-select");
|
||||
write_plugin(data_dir_guard, "Duo_Plugin", two_cap_source);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
REQUIRE(load_and_wait(manager, "Duo_Plugin", error, {"Beta"}));
|
||||
|
||||
REQUIRE(capabilities_of(manager, "Duo_Plugin").size() == 2);
|
||||
|
||||
const auto alpha = find_capability(manager, "Duo_Plugin", "Alpha");
|
||||
const auto beta = find_capability(manager, "Duo_Plugin", "Beta");
|
||||
REQUIRE(alpha != nullptr);
|
||||
REQUIRE(beta != nullptr);
|
||||
|
||||
CHECK_FALSE(alpha->is_enabled());
|
||||
CHECK(beta->is_enabled());
|
||||
|
||||
manager.unload_plugin("Duo_Plugin");
|
||||
}
|
||||
|
||||
TEST_CASE("A cancelled load keeps blocking wait_for_all_plugin_loads until the worker exits", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
// Stalls inside the module import, so the detached load worker is still executing Python while
|
||||
// the test cancels it.
|
||||
const char* const slow_source = R"PY(# /// script
|
||||
# requires-python = ">=3.12"
|
||||
#
|
||||
# [tool.orcaslicer.plugin]
|
||||
# name = "Slow Load Plugin"
|
||||
# version = "1.0"
|
||||
# type = "script"
|
||||
# ///
|
||||
import time
|
||||
|
||||
import orca
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
class Slow(orca.script.ScriptPluginCapabilityBase):
|
||||
def get_name(self):
|
||||
return "Slow"
|
||||
|
||||
def execute(self, ctx):
|
||||
return orca.ExecutionResult.success()
|
||||
|
||||
@orca.plugin
|
||||
class SlowPackage(orca.base):
|
||||
def register_capabilities(self):
|
||||
orca.register_capability(Slow)
|
||||
)PY";
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-cancel");
|
||||
write_plugin(data_dir_guard, "Slow_Load_Plugin", slow_source);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
manager.load_plugin("Slow_Load_Plugin", /*skip_deps=*/true);
|
||||
|
||||
// The key is registered before the worker is spawned, so this is not a race.
|
||||
REQUIRE(manager.is_plugin_load_in_progress("Slow_Load_Plugin"));
|
||||
REQUIRE(manager.cancel_plugin_load("Slow_Load_Plugin"));
|
||||
|
||||
// Cancelling must not release the worker's slot. shutdown() unloads everything and GUI_App
|
||||
// finalizes the interpreter as soon as this wait returns, so reporting "no loads in progress"
|
||||
// while the worker is still inside Python is how the app crashes on exit.
|
||||
CHECK(manager.is_plugin_load_in_progress("Slow_Load_Plugin"));
|
||||
CHECK_FALSE(manager.wait_for_all_plugin_loads(std::chrono::milliseconds(0)));
|
||||
|
||||
// The worker releases the slot itself, once it has unwound.
|
||||
CHECK(manager.wait_for_all_plugin_loads(std::chrono::seconds(60)));
|
||||
CHECK_FALSE(manager.is_plugin_load_in_progress("Slow_Load_Plugin"));
|
||||
CHECK_FALSE(manager.is_plugin_loaded("Slow_Load_Plugin"));
|
||||
}
|
||||
|
||||
TEST_CASE("Loading an unknown plugin key records an error instead of crashing", "[PluginLifecycle][Python]")
|
||||
{
|
||||
// discover_plugins() initializes the plugin system (and with it the interpreter), so this
|
||||
// needs the same explicit teardown as the load tests.
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-missing");
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
// Rejected synchronously: no worker thread is spawned for an unknown key.
|
||||
manager.load_plugin("No_Such_Plugin", /*skip_deps=*/true);
|
||||
|
||||
CHECK_FALSE(manager.is_plugin_loaded("No_Such_Plugin"));
|
||||
CHECK(manager.get_plugin_load_error("No_Such_Plugin") == "Plugin not found: No_Such_Plugin");
|
||||
CHECK(manager.get_plugin_capabilities("No_Such_Plugin").empty());
|
||||
}
|
||||
|
||||
TEST_CASE("The startup auto-load list only contains packages whose sidecar enables them", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-autoload");
|
||||
|
||||
// No sidecar at all: never installed through Orca, so it carries no auto-load intent.
|
||||
write_plugin(data_dir_guard, "Bare_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
// Sidecar with enabled = true: auto-loads.
|
||||
const fs::path on_dir = write_plugin(data_dir_guard, "Enabled_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
PluginInstallState on_state;
|
||||
on_state.installed_from = "local";
|
||||
on_state.enabled = true;
|
||||
REQUIRE(write_install_state(on_dir, on_state));
|
||||
|
||||
// Sidecar with enabled = false: the user turned it off.
|
||||
const fs::path off_dir = write_plugin(data_dir_guard, "Disabled_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
PluginInstallState off_state;
|
||||
off_state.installed_from = "local";
|
||||
off_state.enabled = false;
|
||||
REQUIRE(write_install_state(off_dir, off_state));
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
const std::vector<std::string> keys = manager.get_enabled_plugin_keys();
|
||||
|
||||
CHECK(std::find(keys.begin(), keys.end(), "Enabled_Plugin") != keys.end());
|
||||
CHECK(std::find(keys.begin(), keys.end(), "Disabled_Plugin") == keys.end());
|
||||
CHECK(std::find(keys.begin(), keys.end(), "Bare_Plugin") == keys.end());
|
||||
}
|
||||
|
||||
TEST_CASE("Signing out drops every cloud plugin row, installed or not", "[PluginLifecycle][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("lifecycle-signout");
|
||||
|
||||
// A local package, which must survive sign-out.
|
||||
write_plugin(data_dir_guard, "Echo_Plugin", ECHO_PLUGIN_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
// Two cloud rows: one merely available (nothing installed), one with a local package behind it —
|
||||
// the case that used to linger, unloaded but still listed, until the user hit refresh.
|
||||
PluginDescriptor available;
|
||||
available.plugin_key = "11111111-1111-1111-1111-111111111111";
|
||||
available.name = "Available Cloud Plugin";
|
||||
available.cloud = CloudPluginState{available.plugin_key, /*installed=*/false, false, false, false};
|
||||
|
||||
PluginDescriptor installed;
|
||||
installed.plugin_key = "22222222-2222-2222-2222-222222222222";
|
||||
installed.name = "Installed Cloud Plugin";
|
||||
installed.plugin_root = (data_dir_guard.plugins_dir() / "_subscribed" / "user" / installed.plugin_key).string();
|
||||
installed.cloud = CloudPluginState{installed.plugin_key, /*installed=*/true, false, false, false};
|
||||
|
||||
manager.update_cloud_metadata({available, installed});
|
||||
|
||||
const auto has_key = [&manager](const std::string& key) {
|
||||
PluginDescriptor descriptor;
|
||||
return manager.try_get_plugin_descriptor(key, descriptor);
|
||||
};
|
||||
|
||||
REQUIRE(has_key(available.plugin_key));
|
||||
REQUIRE(has_key(installed.plugin_key));
|
||||
REQUIRE(has_key("Echo_Plugin"));
|
||||
|
||||
// Sign out. The per-user _subscribed directory stops being scanned, so both cloud rows are now
|
||||
// stale and must go — not just the one with nothing installed behind it.
|
||||
manager.unload_cloud_plugins();
|
||||
manager.clear_cloud_plugin_metadata();
|
||||
manager.set_cloud_user("");
|
||||
|
||||
CHECK_FALSE(has_key(available.plugin_key));
|
||||
CHECK_FALSE(has_key(installed.plugin_key));
|
||||
CHECK(has_key("Echo_Plugin"));
|
||||
}
|
||||
|
||||
TEST_CASE("Unloading a plugin that is not loaded is a no-op", "[PluginLifecycle]")
|
||||
{
|
||||
ScopedDataDir data_dir_guard("lifecycle-noop-unload");
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
|
||||
// Current behavior: unloading an unknown key succeeds (it fires the unload callbacks and
|
||||
// reports success) rather than reporting "nothing to unload".
|
||||
CHECK(manager.unload_plugin("No_Such_Plugin"));
|
||||
CHECK_FALSE(manager.is_plugin_loaded("No_Such_Plugin"));
|
||||
}
|
||||
189
tests/slic3rutils/test_plugin_sort.cpp
Normal file
189
tests/slic3rutils/test_plugin_sort.cpp
Normal file
@@ -0,0 +1,189 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <slic3r/GUI/PluginSort.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using Slic3r::GUI::compare_ascii_case_insensitive_natural;
|
||||
using Slic3r::GUI::PluginSortKey;
|
||||
using Slic3r::GUI::PluginSortOrder;
|
||||
using Slic3r::GUI::PluginSource;
|
||||
using Slic3r::GUI::PluginStatus;
|
||||
using Slic3r::GUI::plugin_sort_key_from_string;
|
||||
using Slic3r::GUI::plugin_sort_order_from_string;
|
||||
using Slic3r::GUI::sort_plugin_items_for_dialog;
|
||||
|
||||
namespace {
|
||||
|
||||
struct SortFixtureItem
|
||||
{
|
||||
std::string plugin_key;
|
||||
PluginSource source;
|
||||
PluginStatus status;
|
||||
std::string type_key;
|
||||
std::string display_name;
|
||||
std::string sort_version;
|
||||
};
|
||||
|
||||
std::vector<std::string> keys(const std::vector<SortFixtureItem>& items)
|
||||
{
|
||||
std::vector<std::string> result;
|
||||
result.reserve(items.size());
|
||||
for (const SortFixtureItem& item : items)
|
||||
result.push_back(item.plugin_key);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("plugin dialog status sort uses requested priority and base-order ties", "[plugin][sort]")
|
||||
{
|
||||
std::vector<SortFixtureItem> items = {
|
||||
{"local_inactive", PluginSource::Local, PluginStatus::Inactive, "script", "Local Inactive"},
|
||||
{"mine_error", PluginSource::Mine, PluginStatus::Error, "script", "Mine Error"},
|
||||
{"mine_activated", PluginSource::Mine, PluginStatus::Activated, "script", "Mine Activated"},
|
||||
{"local_activated", PluginSource::Local, PluginStatus::Activated, "script", "Local Activated"},
|
||||
{"subscribed_loading", PluginSource::Subscribed, PluginStatus::Loading, "script", "Subscribed Loading"},
|
||||
};
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Status, PluginSortOrder::Asc);
|
||||
|
||||
// why: local_activated and mine_activated tie on Status, so base order breaks the tie by name
|
||||
// (case-insensitive) - "Local Activated" before "Mine Activated".
|
||||
const std::vector<std::string> expected = {
|
||||
"local_activated",
|
||||
"mine_activated",
|
||||
"mine_error",
|
||||
"local_inactive",
|
||||
"subscribed_loading",
|
||||
};
|
||||
CHECK(keys(items) == expected);
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Status, PluginSortOrder::Desc);
|
||||
|
||||
// why: Desc reverses the status ordinal, but the Activated tie still resolves by ascending
|
||||
// base order (name: "Local Activated" before "Mine Activated") - direction only flips the key.
|
||||
const std::vector<std::string> desc_expected = {
|
||||
"subscribed_loading",
|
||||
"local_inactive",
|
||||
"mine_error",
|
||||
"local_activated",
|
||||
"mine_activated",
|
||||
};
|
||||
CHECK(keys(items) == desc_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin dialog source sort uses enum priority", "[plugin][sort]")
|
||||
{
|
||||
std::vector<SortFixtureItem> items = {
|
||||
{"local", PluginSource::Local, PluginStatus::Activated, "script", "Local"},
|
||||
{"mine", PluginSource::Mine, PluginStatus::Activated, "script", "Mine"},
|
||||
{"subscribed", PluginSource::Subscribed, PluginStatus::Activated, "script", "Subscribed"},
|
||||
};
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Source, PluginSortOrder::Asc);
|
||||
const std::vector<std::string> asc_expected = {"mine", "subscribed", "local"};
|
||||
CHECK(keys(items) == asc_expected);
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Source, PluginSortOrder::Desc);
|
||||
const std::vector<std::string> desc_expected = {"local", "subscribed", "mine"};
|
||||
CHECK(keys(items) == desc_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin dialog version sort is semver-aware with base-order ties", "[plugin][sort]")
|
||||
{
|
||||
std::vector<SortFixtureItem> items = {
|
||||
{"v_1_2_0", PluginSource::Local, PluginStatus::Activated, "script", "B", "1.2.0"},
|
||||
{"v_1_10_0", PluginSource::Local, PluginStatus::Activated, "script", "A", "1.10.0"},
|
||||
{"v_0_9_3", PluginSource::Local, PluginStatus::Activated, "script", "C", "0.9.3"},
|
||||
};
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Version, PluginSortOrder::Asc);
|
||||
// why: semver numeric compare - 1.10.0 > 1.2.0 (not lexical "1.10" < "1.2"), so ascending is
|
||||
// 0.9.3 < 1.2.0 < 1.10.0.
|
||||
const std::vector<std::string> asc_expected = {"v_0_9_3", "v_1_2_0", "v_1_10_0"};
|
||||
CHECK(keys(items) == asc_expected);
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Version, PluginSortOrder::Desc);
|
||||
const std::vector<std::string> desc_expected = {"v_1_10_0", "v_1_2_0", "v_0_9_3"};
|
||||
CHECK(keys(items) == desc_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin dialog name sort is case-insensitive and numeric-aware", "[plugin][sort]")
|
||||
{
|
||||
std::vector<SortFixtureItem> items = {
|
||||
{"rig10", PluginSource::Local, PluginStatus::Activated, "script", "Rig 10"},
|
||||
{"ada_lower", PluginSource::Local, PluginStatus::Activated, "script", "ada"},
|
||||
{"rig2", PluginSource::Local, PluginStatus::Activated, "script", "Rig 2"},
|
||||
{"ada_upper", PluginSource::Local, PluginStatus::Activated, "script", "Ada"},
|
||||
};
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Name, PluginSortOrder::Asc);
|
||||
|
||||
// why: "Ada"/"ada" tie on the case-insensitive name (primary AND base name level), so the tie
|
||||
// falls through source/status/type to plugin_key: "ada_lower" before "ada_upper".
|
||||
const std::vector<std::string> expected = {"ada_lower", "ada_upper", "rig2", "rig10"};
|
||||
CHECK(keys(items) == expected);
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::Name, PluginSortOrder::Desc);
|
||||
|
||||
// why: names reverse ("Rig 10" before "Rig 2"), but "Ada"/"ada" tie on the case-insensitive
|
||||
// key and keep ascending base order, which resolves by plugin_key ("ada_lower" < "ada_upper").
|
||||
const std::vector<std::string> desc_expected = {"rig10", "rig2", "ada_lower", "ada_upper"};
|
||||
CHECK(keys(items) == desc_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("natural compare handles digits, case, prefixes and leading zeros", "[plugin][sort]")
|
||||
{
|
||||
// numeric runs compare by value, not lexically
|
||||
CHECK(compare_ascii_case_insensitive_natural("item2", "item10") < 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("item10", "item2") > 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("2", "10") < 0);
|
||||
|
||||
// case is ignored on the primary comparison
|
||||
CHECK(compare_ascii_case_insensitive_natural("Camera", "camera") == 0);
|
||||
|
||||
// a prefix is less than the longer string it prefixes
|
||||
CHECK(compare_ascii_case_insensitive_natural("app", "apple") < 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("apple", "app") > 0);
|
||||
|
||||
// equal numeric value: fewer leading zeros wins the tie
|
||||
CHECK(compare_ascii_case_insensitive_natural("1", "01") < 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("01", "1") > 0);
|
||||
|
||||
// reflexivity and empty-string boundaries
|
||||
CHECK(compare_ascii_case_insensitive_natural("plugin", "plugin") == 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("", "") == 0);
|
||||
CHECK(compare_ascii_case_insensitive_natural("", "a") < 0);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin dialog None sort key falls to ascending base order in both directions", "[plugin][sort]")
|
||||
{
|
||||
std::vector<SortFixtureItem> items = {
|
||||
{"z_mine", PluginSource::Mine, PluginStatus::Activated, "script", "Zebra"},
|
||||
{"a_local", PluginSource::Local, PluginStatus::Activated, "script", "Apple"},
|
||||
{"m_sub", PluginSource::Subscribed, PluginStatus::Error, "script", "Mango"},
|
||||
};
|
||||
|
||||
// why: no primary key -> pure name-first base order (Apple < Mango < Zebra). A source-first
|
||||
// baseline would instead give {z_mine, m_sub, a_local}, so this pins the name-first order.
|
||||
const std::vector<std::string> base_expected = {"a_local", "m_sub", "z_mine"};
|
||||
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::None, PluginSortOrder::Asc);
|
||||
CHECK(keys(items) == base_expected);
|
||||
|
||||
// why: None has no direction - Desc must not reverse the baseline.
|
||||
sort_plugin_items_for_dialog(items, PluginSortKey::None, PluginSortOrder::Desc);
|
||||
CHECK(keys(items) == base_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("plugin dialog sort request parsing keeps previous state on invalid values", "[plugin][sort]")
|
||||
{
|
||||
CHECK(plugin_sort_key_from_string("source", PluginSortKey::Status) == PluginSortKey::Source);
|
||||
CHECK(plugin_sort_key_from_string("none", PluginSortKey::Status) == PluginSortKey::None);
|
||||
CHECK(plugin_sort_key_from_string("missing", PluginSortKey::Name) == PluginSortKey::Name);
|
||||
|
||||
CHECK(plugin_sort_order_from_string("desc", PluginSortOrder::Asc) == PluginSortOrder::Desc);
|
||||
CHECK(plugin_sort_order_from_string("down", PluginSortOrder::Asc) == PluginSortOrder::Asc);
|
||||
}
|
||||
682
tests/slic3rutils/test_slicing_pipeline_bindings.cpp
Normal file
682
tests/slic3rutils/test_slicing_pipeline_bindings.cpp
Normal file
@@ -0,0 +1,682 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include "slic3r/plugin/PythonPluginInterface.hpp"
|
||||
using namespace Slic3r;
|
||||
|
||||
TEST_CASE("SlicingPipeline capability-type string maps round-trip", "[slicing_pipeline]") {
|
||||
CHECK(plugin_capability_type_to_string(PluginCapabilityType::SlicingPipeline) == "slicing-pipeline");
|
||||
CHECK(plugin_capability_type_display_name(PluginCapabilityType::SlicingPipeline) == "Slicing Pipeline");
|
||||
CHECK(plugin_capability_type_from_string("slicing-pipeline") == PluginCapabilityType::SlicingPipeline);
|
||||
CHECK(plugin_capability_type_from_string("SLICING-PIPELINE") == PluginCapabilityType::SlicingPipeline);
|
||||
CHECK(plugin_capability_type_from_string("nope") == PluginCapabilityType::Unknown);
|
||||
}
|
||||
|
||||
#include "python_test_support.hpp"
|
||||
#include "slic3r/plugin/PluginBindingUtils.hpp"
|
||||
#include "slic3r/plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp"
|
||||
#include "libslic3r/Point.hpp"
|
||||
#include "libslic3r/ExPolygon.hpp"
|
||||
#include "libslic3r/Surface.hpp"
|
||||
#include "libslic3r/Layer.hpp"
|
||||
#include "libslic3r/ExtrusionEntity.hpp"
|
||||
#include "libslic3r/ExtrusionEntityCollection.hpp"
|
||||
#include <catch2/matchers/catch_matchers_floating_point.hpp>
|
||||
#include <pybind11/embed.h>
|
||||
#include <pybind11/numpy.h>
|
||||
namespace py = pybind11;
|
||||
|
||||
TEST_CASE("make_readonly_rows builds a read-only (N,2) int64 view", "[slicing_pipeline]") {
|
||||
ensure_python_initialized(); // helper already used by test_plugin_host_api.cpp
|
||||
py::gil_scoped_acquire gil;
|
||||
|
||||
// make_readonly_rows() constructs a py::array_t, which requires numpy to be
|
||||
// importable in the embedded interpreter. The unit-test interpreter ships no
|
||||
// site-packages (same condition test_plugin_host_api.cpp's TriangleMesh numpy
|
||||
// test guards against), so skip the array-backed assertions when numpy is
|
||||
// unavailable there rather than fail on an environment quirk.
|
||||
bool have_numpy = false;
|
||||
try {
|
||||
py::module_::import("numpy");
|
||||
have_numpy = true;
|
||||
} catch (const py::error_already_set&) {
|
||||
have_numpy = false;
|
||||
}
|
||||
if (!have_numpy) {
|
||||
SKIP("numpy unavailable in unit-test interpreter");
|
||||
}
|
||||
|
||||
static Slic3r::Points pts = { Slic3r::Point(10, 20), Slic3r::Point(30, 40) };
|
||||
py::capsule keepalive(&pts, [](void*){});
|
||||
py::array a = Slic3r::make_readonly_rows<coord_t, 2>(keepalive, pts.front().data(), (py::ssize_t)pts.size());
|
||||
CHECK(a.dtype().kind() == 'i');
|
||||
CHECK(a.itemsize() == 8); // int64
|
||||
CHECK(a.shape(0) == 2);
|
||||
CHECK(a.shape(1) == 2);
|
||||
CHECK_FALSE(a.writeable());
|
||||
auto r = a.unchecked<coord_t, 2>();
|
||||
CHECK(r(0,0) == 10); CHECK(r(1,1) == 40);
|
||||
}
|
||||
|
||||
TEST_CASE("make_writable_rows builds a writable (N,2) int64 view that aliases the buffer", "[slicing_pipeline]") {
|
||||
ensure_python_initialized();
|
||||
py::gil_scoped_acquire gil;
|
||||
bool have_numpy = false;
|
||||
try { py::module_::import("numpy"); have_numpy = true; }
|
||||
catch (const py::error_already_set&) { have_numpy = false; }
|
||||
if (!have_numpy) SKIP("numpy unavailable in unit-test interpreter");
|
||||
|
||||
static Slic3r::Points pts = { Slic3r::Point(10, 20), Slic3r::Point(30, 40) };
|
||||
py::capsule keepalive(&pts, [](void*){});
|
||||
py::array a = Slic3r::make_writable_rows<coord_t, 2>(keepalive, pts.front().data(), (py::ssize_t)pts.size());
|
||||
CHECK(a.writeable());
|
||||
// Writing through the view mutates the C++ buffer (zero-copy alias).
|
||||
a.attr("__setitem__")(py::make_tuple(0, 0), py::int_(99));
|
||||
CHECK(pts.front().x() == 99);
|
||||
}
|
||||
|
||||
TEST_CASE("orca.slicing module: Step enum, context, and a Python capability can execute", "[slicing_pipeline]") {
|
||||
ensure_python_initialized();
|
||||
import_orca_module(); // forces PythonPluginBridge::instance() (see import_orca_module in python_test_support.hpp)
|
||||
py::gil_scoped_acquire gil;
|
||||
py::module_ orca = py::module_::import("orca");
|
||||
REQUIRE(py::hasattr(orca, "slicing"));
|
||||
py::object slicing = orca.attr("slicing");
|
||||
CHECK(py::hasattr(slicing, "Step"));
|
||||
CHECK(py::hasattr(slicing.attr("Step"), "posSlice"));
|
||||
CHECK(py::hasattr(slicing.attr("Step"), "psGCodePostProcess"));
|
||||
CHECK(py::hasattr(slicing, "SlicingPipelineContext"));
|
||||
CHECK(py::hasattr(slicing, "SlicingPipelineCapabilityBase"));
|
||||
|
||||
// A trivial Python subclass whose execute() reports success, invoked via the C++ trampoline.
|
||||
py::exec(R"(
|
||||
import orca
|
||||
class Probe(orca.slicing.SlicingPipelineCapabilityBase):
|
||||
def get_name(self): return "probe"
|
||||
def execute(self, ctx): return orca.ExecutionResult.success("ok")
|
||||
_probe = Probe()
|
||||
)");
|
||||
// (Full C++ trampoline invocation with a real context is exercised elsewhere.)
|
||||
}
|
||||
|
||||
TEST_CASE("orca.slicing is workflow-only: context exposes raw print/object; view classes are gone", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::module_ orca = py::module_::import("orca");
|
||||
py::object slicing = orca.attr("slicing");
|
||||
|
||||
// Context surface: raw graph entry points + workflow accessors.
|
||||
for (const char* name : { "print", "object", "config_value", "cancelled",
|
||||
"orca_version", "step" })
|
||||
CHECK(py::hasattr(slicing.attr("SlicingPipelineContext"), name));
|
||||
|
||||
// The wrapper layer is gone.
|
||||
for (const char* legacy : { "ExPolygonView", "SurfaceView", "LayerRegionView",
|
||||
"LayerView", "PrintObjectView", "PathData", "SurfaceType" })
|
||||
CHECK_FALSE(py::hasattr(slicing, legacy));
|
||||
|
||||
// unscale() stays in orca.slicing and reads the live SCALING_FACTOR.
|
||||
const coord_t scaled10 = (coord_t) scale_(10.0);
|
||||
double mm = slicing.attr("unscale")(scaled10).cast<double>();
|
||||
CHECK_THAT(mm, WithinRel(10.0, 1e-9));
|
||||
|
||||
// A default context casts print/object to None (no dangling wrapper).
|
||||
Slic3r::SlicingPipelineContext ctx;
|
||||
py::object pyctx = py::cast(&ctx, py::return_value_policy::reference);
|
||||
CHECK(pyctx.attr("print").is_none());
|
||||
CHECK(pyctx.attr("object").is_none());
|
||||
}
|
||||
|
||||
#include "libslic3r/PrintConfig.hpp" // DynamicPrintConfig for the psGCodePostProcess context
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/nowide/fstream.hpp>
|
||||
#include <sstream>
|
||||
|
||||
// psGCodePostProcess is the merged post-processing seam: no live Print (print/object are None), the
|
||||
// plugin edits the file at ctx.gcode_path in place, and ctx.config_value() falls back to the config
|
||||
// the export path handed in. Exercising the real bindings by calling the Python execute() directly
|
||||
// (not the C++ audit trampoline) keeps this a pure binding-surface test.
|
||||
TEST_CASE("orca.slicing psGCodePostProcess context: file edit in place + config fallback", "[slicing_pipeline]") {
|
||||
namespace fs = boost::filesystem;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
|
||||
const fs::path gpath = fs::temp_directory_path() / fs::unique_path("orca_pp_%%%%-%%%%.gcode");
|
||||
{
|
||||
boost::nowide::ofstream ofs(gpath.string());
|
||||
ofs << "; header\nG1 X0 Y0\n";
|
||||
}
|
||||
|
||||
// Config the plugin reads back through ctx.config_value() (there is no live Print at this step).
|
||||
Slic3r::DynamicPrintConfig config = Slic3r::DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("layer_height", new Slic3r::ConfigOptionFloat(0.2));
|
||||
|
||||
Slic3r::SlicingPipelineContext ctx;
|
||||
ctx.orca_version = "test";
|
||||
ctx.step = Slic3r::SlicingPipelineStepPlugin::psGCodePostProcess;
|
||||
ctx.gcode_path = gpath.string();
|
||||
ctx.host = "File";
|
||||
ctx.output_name = "final.gcode";
|
||||
ctx.full_config = &config; // print stays null
|
||||
|
||||
py::object pyctx = py::cast(&ctx, py::return_value_policy::reference);
|
||||
CHECK(pyctx.attr("gcode_path").cast<std::string>() == gpath.string());
|
||||
CHECK(pyctx.attr("host").cast<std::string>() == "File");
|
||||
CHECK(pyctx.attr("output_name").cast<std::string>() == "final.gcode");
|
||||
CHECK(pyctx.attr("print").is_none());
|
||||
CHECK(pyctx.attr("object").is_none());
|
||||
CHECK(pyctx.attr("step").cast<Slic3r::SlicingPipelineStepPlugin>()
|
||||
== Slic3r::SlicingPipelineStepPlugin::psGCodePostProcess);
|
||||
CHECK_FALSE(pyctx.attr("cancelled")().cast<bool>()); // null print -> not cancelled
|
||||
// config_value() resolves from full_config when print is null; unknown keys are None.
|
||||
CHECK_FALSE(pyctx.attr("config_value")("layer_height").is_none());
|
||||
CHECK(pyctx.attr("config_value")("this_key_does_not_exist").is_none());
|
||||
|
||||
// A Python capability edits the file in place through ctx.gcode_path. Calling execute() directly
|
||||
// in Python dispatches to the Python method (no C++ trampoline), so this needs no audit context.
|
||||
py::module_ main = py::module_::import("__main__");
|
||||
main.attr("_pp_ctx") = pyctx;
|
||||
py::exec(R"(
|
||||
import orca
|
||||
class Stamp(orca.slicing.SlicingPipelineCapabilityBase):
|
||||
def get_name(self): return "stamp"
|
||||
def execute(self, ctx):
|
||||
assert ctx.step == orca.slicing.Step.psGCodePostProcess
|
||||
assert ctx.print is None and ctx.object is None
|
||||
with open(ctx.gcode_path, "a") as f:
|
||||
f.write("; stamped by " + ctx.host + "\n")
|
||||
return orca.ExecutionResult.success("ok")
|
||||
_pp_result = Stamp().execute(_pp_ctx)
|
||||
)");
|
||||
CHECK(main.attr("_pp_result").attr("message").cast<std::string>() == std::string("ok"));
|
||||
|
||||
std::string contents;
|
||||
{
|
||||
boost::nowide::ifstream ifs(gpath.string());
|
||||
std::stringstream ss; ss << ifs.rdbuf(); contents = ss.str();
|
||||
}
|
||||
CHECK(contents.find("; stamped by File") != std::string::npos);
|
||||
fs::remove(gpath);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Toolpath helpers for the raw-graph tests.
|
||||
//
|
||||
// LayerRegion's ctor is protected (constructed only by Layer/PrintObject). A
|
||||
// trivial derived struct lets a unit test build one with null layer/region
|
||||
// pointers — the extrusion accessors only read the public `perimeters`/`fills`
|
||||
// collections, never the layer/region back-pointers.
|
||||
// ---------------------------------------------------------------------------
|
||||
namespace {
|
||||
struct TestLayerRegion : Slic3r::LayerRegion {
|
||||
TestLayerRegion() : Slic3r::LayerRegion(nullptr, nullptr) {}
|
||||
};
|
||||
|
||||
// Build a realistic nested perimeters collection into `region.perimeters`:
|
||||
// perimeters (outer) -> inner collection -> [ ExtrusionLoop(pathA), ExtrusionPath(pathB) ]
|
||||
// This exercises both the recursive descent through nested collections and the
|
||||
// decomposition of an ExtrusionLoop into its contained ExtrusionPath (flatten()
|
||||
// does NOT decompose loops, hence the hand-rolled recursive walk).
|
||||
static void build_nested_perimeters(TestLayerRegion& region) {
|
||||
using namespace Slic3r;
|
||||
ExtrusionPath pathA(erExternalPerimeter); // -> "Outer wall"
|
||||
pathA.mm3_per_mm = 0.05; pathA.width = 0.45f; pathA.height = 0.20f;
|
||||
pathA.polyline.points = { Point3(0, 0, 0), Point3(10, 0, 0), Point3(10, 10, 0) };
|
||||
|
||||
ExtrusionPath pathB(erInternalInfill); // -> "Sparse infill"
|
||||
pathB.mm3_per_mm = 0.03; pathB.width = 0.40f; pathB.height = 0.20f;
|
||||
pathB.polyline.points = { Point3(1, 1, 0), Point3(2, 1, 0), Point3(2, 2, 0) };
|
||||
|
||||
ExtrusionEntityCollection inner;
|
||||
inner.append(ExtrusionLoop(pathA)); // clone_move
|
||||
inner.append(pathB); // clone
|
||||
region.perimeters.append(inner); // nested (deep clone)
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raw Print-graph data model (orca.host) — replaces the *View wrapper API.
|
||||
// LIFETIME: raw bindings follow C++ semantics — references into the slicing
|
||||
// graph are valid during execute(ctx) and invalidated by container-replacing
|
||||
// mutators, exactly like std::vector iterators.
|
||||
// ---------------------------------------------------------------------------
|
||||
TEST_CASE("orca.host leaf geometry: Surface/ExPolygon/Polygon raw bindings", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
using Catch::Matchers::WithinAbs;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
|
||||
for (const char* name : { "SurfaceType", "Polygon", "ExPolygon", "Surface", "SurfaceCollection" })
|
||||
CHECK(py::hasattr(host, name));
|
||||
|
||||
// SurfaceType enum values round-trip to the C++ enumerators (moved from orca.slicing).
|
||||
py::object ST = host.attr("SurfaceType");
|
||||
CHECK(ST.attr("stTop").cast<Slic3r::SurfaceType>() == Slic3r::stTop);
|
||||
CHECK(ST.attr("stInternalSolid").cast<Slic3r::SurfaceType>() == Slic3r::stInternalSolid);
|
||||
CHECK(ST.attr("stPerimeter").cast<Slic3r::SurfaceType>() == Slic3r::stPerimeter);
|
||||
|
||||
// Raw Surface: scalar reads + WRITABLE surface_type (replaces SurfaceView.set_type).
|
||||
Slic3r::Surface surf(Slic3r::stInternalSolid);
|
||||
surf.thickness = 0.4;
|
||||
surf.bridge_angle = -1.0;
|
||||
surf.extra_perimeters = 2;
|
||||
py::object sv = py::cast(&surf, py::return_value_policy::reference);
|
||||
CHECK(sv.attr("surface_type").cast<Slic3r::SurfaceType>() == Slic3r::stInternalSolid);
|
||||
CHECK_THAT(sv.attr("thickness").cast<double>(), WithinRel(0.4, 1e-9));
|
||||
CHECK_THAT(sv.attr("bridge_angle").cast<double>(), WithinAbs(-1.0, 1e-12));
|
||||
CHECK(sv.attr("extra_perimeters").cast<int>() == 2);
|
||||
sv.attr("surface_type") = host.attr("SurfaceType").attr("stTop");
|
||||
CHECK(surf.surface_type == Slic3r::stTop); // C++ side reflects the assignment
|
||||
|
||||
// ExPolygon navigation without numpy: contour is a Polygon, holes an empty list.
|
||||
py::object exv = sv.attr("expolygon");
|
||||
CHECK(py::hasattr(exv, "contour"));
|
||||
CHECK(exv.attr("holes").cast<py::list>().size() == 0);
|
||||
CHECK(exv.attr("contour").attr("size")().cast<size_t>() == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host Surface/SurfaceCollection: construct, writable members, set()", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
py::object ST = host.attr("SurfaceType");
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
|
||||
// Build an ExPolygon (Point idiom) and a Surface from it.
|
||||
py::object P = host.attr("Polygon")();
|
||||
P.attr("append")(host.attr("Point")(0, 0));
|
||||
P.attr("append")(host.attr("Point")(s, 0));
|
||||
P.attr("append")(host.attr("Point")(s, s));
|
||||
P.attr("append")(host.attr("Point")(0, s));
|
||||
py::object ex = host.attr("ExPolygon")(P);
|
||||
py::object surf = host.attr("Surface")(ST.attr("stTop"), ex);
|
||||
CHECK(surf.attr("surface_type").cast<Slic3r::SurfaceType>() == Slic3r::stTop);
|
||||
CHECK(surf.attr("is_top")().cast<bool>());
|
||||
CHECK_THAT(surf.attr("area")().cast<double>(), WithinRel((double) s * (double) s, 1e-9));
|
||||
surf.attr("thickness") = py::float_(0.3);
|
||||
CHECK_THAT(surf.attr("thickness").cast<double>(), WithinRel(0.3, 1e-9));
|
||||
|
||||
// SurfaceCollection.set(expolys, type): replace all surfaces from a list of ExPolygon tagged with one SurfaceType.
|
||||
Slic3r::SurfaceCollection coll;
|
||||
py::object cv = py::cast(&coll, py::return_value_policy::reference);
|
||||
py::list expolys; expolys.append(ex);
|
||||
cv.attr("set")(expolys, ST.attr("stInternalSolid"));
|
||||
REQUIRE(coll.surfaces.size() == 1);
|
||||
CHECK(coll.surfaces.front().surface_type == Slic3r::stInternalSolid);
|
||||
CHECK(cv.attr("has")(ST.attr("stInternalSolid")).cast<bool>());
|
||||
cv.attr("clear")();
|
||||
CHECK(coll.surfaces.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host Point: construct, read/write coords, arithmetic", "[slicing_pipeline]") {
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
REQUIRE(py::hasattr(host, "Point"));
|
||||
py::object p = host.attr("Point")(3, 4);
|
||||
CHECK(p.attr("x").cast<coord_t>() == 3);
|
||||
CHECK(p.attr("y").cast<coord_t>() == 4);
|
||||
p.attr("x") = py::int_(7);
|
||||
CHECK(p.attr("x").cast<coord_t>() == 7);
|
||||
py::object q = host.attr("Point")(1, 2);
|
||||
py::object sum = p.attr("__add__")(q);
|
||||
CHECK(sum.attr("x").cast<coord_t>() == 8);
|
||||
CHECK(sum.attr("y").cast<coord_t>() == 6);
|
||||
|
||||
// __mul__ must scale as a double, not truncate to int64 before multiplying.
|
||||
py::object h = host.attr("Point")(10, 20).attr("__mul__")(py::float_(0.5));
|
||||
CHECK(h.attr("x").cast<coord_t>() == 5);
|
||||
CHECK(h.attr("y").cast<coord_t>() == 10);
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host Polygon: writable as_array aliases buffer; Point refs; set_points; offset", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
Slic3r::Polygon poly;
|
||||
poly.points = { Slic3r::Point(0, 0), Slic3r::Point(s, 0), Slic3r::Point(s, s), Slic3r::Point(0, s) };
|
||||
py::object pv = py::cast(&poly, py::return_value_policy::reference);
|
||||
|
||||
// Non-array surface works without numpy.
|
||||
CHECK(pv.attr("size")().cast<size_t>() == 4);
|
||||
CHECK(pv.attr("is_counter_clockwise")().cast<bool>());
|
||||
CHECK_THAT(pv.attr("area")().cast<double>(), WithinRel((double) s * (double) s, 1e-9));
|
||||
// Point-object idiom: editing a returned Point ref mutates the buffer in place.
|
||||
py::list pts = pv.attr("points").cast<py::list>();
|
||||
REQUIRE(pts.size() == 4);
|
||||
pts[0].attr("x") = py::int_(5);
|
||||
CHECK(poly.points[0].x() == 5);
|
||||
poly.points[0].x() = 0; // restore
|
||||
|
||||
// offset() returns new geometry (ClipperUtils bound as a method).
|
||||
py::list shrunk = pv.attr("offset")(py::int_(-(coord_t)scale_(1.0))).cast<py::list>();
|
||||
CHECK(shrunk.size() >= 1);
|
||||
|
||||
bool have_numpy = false;
|
||||
try { py::module_::import("numpy"); have_numpy = true; }
|
||||
catch (const py::error_already_set&) { have_numpy = false; }
|
||||
if (!have_numpy) SKIP("numpy unavailable: array-backed assertions skipped");
|
||||
|
||||
py::module_ np = py::module_::import("numpy");
|
||||
py::array a = pv.attr("as_array")().cast<py::array>();
|
||||
CHECK(a.dtype().kind() == 'i');
|
||||
CHECK(a.itemsize() == 8);
|
||||
CHECK(a.shape(0) == 4);
|
||||
CHECK(a.shape(1) == 2);
|
||||
CHECK(a.writeable()); // writable now
|
||||
a.attr("__setitem__")(py::make_tuple(0, 0), py::int_(123));
|
||||
CHECK(poly.points[0].x() == 123); // in-place bulk edit
|
||||
// set_points replaces contents (count-changing).
|
||||
py::object i64 = np.attr("int64");
|
||||
py::list rows;
|
||||
rows.append(py::make_tuple(0, 0)); rows.append(py::make_tuple(s, 0)); rows.append(py::make_tuple(s, s));
|
||||
pv.attr("set_points")(np.attr("array")(rows, py::arg("dtype") = i64));
|
||||
CHECK(poly.points.size() == 3);
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host ExPolygon: construct, writable contour/holes, transforms, boolean ops", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
|
||||
// Construct from Polygon objects (Point idiom, no numpy).
|
||||
py::object P = host.attr("Polygon")();
|
||||
P.attr("append")(host.attr("Point")(0, 0));
|
||||
P.attr("append")(host.attr("Point")(s, 0));
|
||||
P.attr("append")(host.attr("Point")(s, s));
|
||||
P.attr("append")(host.attr("Point")(0, s));
|
||||
py::object ex = host.attr("ExPolygon")(P);
|
||||
CHECK_THAT(ex.attr("area")().cast<double>(), WithinRel((double) s * (double) s, 1e-9));
|
||||
CHECK(ex.attr("num_contours")().cast<size_t>() == 1);
|
||||
CHECK(ex.attr("contour").attr("size")().cast<size_t>() == 4);
|
||||
|
||||
// In-place transform mutates the geometry.
|
||||
ex.attr("translate")(py::float_(1000.0), py::float_(0.0));
|
||||
// Boolean op returns new geometry: A minus a smaller inset of A is a non-empty ring set.
|
||||
py::list inset = ex.attr("offset")(py::int_(-(coord_t)scale_(1.0))).cast<py::list>();
|
||||
REQUIRE(inset.size() >= 1);
|
||||
py::list ring = ex.attr("diff_ex")(inset[0]).cast<py::list>();
|
||||
CHECK(ring.size() >= 1);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// Nested collection: outer -> inner -> [ ExtrusionLoop(pathA), ExtrusionPath(pathB) ].
|
||||
// Exercises polymorphic downcast of .entities and loop decomposition in flatten_paths().
|
||||
static Slic3r::ExtrusionEntityCollection build_nested_collection() {
|
||||
using namespace Slic3r;
|
||||
ExtrusionPath pathA(erExternalPerimeter); // -> "Outer wall"
|
||||
pathA.mm3_per_mm = 0.05; pathA.width = 0.45f; pathA.height = 0.20f;
|
||||
pathA.polyline.points = { Point3(0, 0, 0), Point3(10, 0, 0), Point3(10, 10, 0) };
|
||||
|
||||
ExtrusionPath pathB(erInternalInfill); // -> "Sparse infill"
|
||||
pathB.mm3_per_mm = 0.03; pathB.width = 0.40f; pathB.height = 0.20f;
|
||||
pathB.polyline.points = { Point3(1, 1, 0), Point3(2, 1, 0), Point3(2, 2, 0) };
|
||||
|
||||
ExtrusionEntityCollection inner;
|
||||
inner.append(ExtrusionLoop(pathA));
|
||||
inner.append(pathB);
|
||||
ExtrusionEntityCollection outer;
|
||||
outer.append(inner);
|
||||
return outer;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("orca.host extrusion tree: polymorphic entities + flatten_paths", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
for (const char* name : { "ExtrusionEntity", "ExtrusionPath", "ExtrusionLoop",
|
||||
"ExtrusionMultiPath", "ExtrusionEntityCollection", "PrintRegion" })
|
||||
CHECK(py::hasattr(host, name));
|
||||
|
||||
Slic3r::ExtrusionEntityCollection outer = build_nested_collection();
|
||||
py::object coll = py::cast(&outer, py::return_value_policy::reference);
|
||||
|
||||
// .entities downcasts: the single child is a collection; ITS children are a loop + a path.
|
||||
py::list kids = coll.attr("entities").cast<py::list>();
|
||||
REQUIRE(kids.size() == 1);
|
||||
py::list inner_kids = kids[0].attr("entities").cast<py::list>();
|
||||
REQUIRE(inner_kids.size() == 2);
|
||||
CHECK(py::hasattr(inner_kids[0], "paths")); // ExtrusionLoop binding
|
||||
CHECK(py::hasattr(inner_kids[1], "width")); // ExtrusionPath binding
|
||||
|
||||
// flatten_paths: loop decomposed, scalars readable.
|
||||
py::list ps = coll.attr("flatten_paths")().cast<py::list>();
|
||||
REQUIRE(ps.size() == 2);
|
||||
CHECK(ps[0].attr("role").cast<std::string>() == "Outer wall");
|
||||
CHECK_THAT(ps[0].attr("width").cast<double>(), WithinRel(0.45, 1e-6));
|
||||
CHECK_THAT(ps[0].attr("mm3_per_mm").cast<double>(), WithinRel(0.05, 1e-9));
|
||||
CHECK(ps[1].attr("role").cast<std::string>() == "Sparse infill");
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host ExtrusionPath.points() is a read-only (N,3) int64 view", "[slicing_pipeline]") {
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
bool have_numpy = false;
|
||||
try { py::module_::import("numpy"); have_numpy = true; }
|
||||
catch (const py::error_already_set&) { have_numpy = false; }
|
||||
if (!have_numpy) SKIP("numpy unavailable in unit-test interpreter");
|
||||
|
||||
Slic3r::ExtrusionEntityCollection outer = build_nested_collection();
|
||||
py::object coll = py::cast(&outer, py::return_value_policy::reference);
|
||||
py::list ps = coll.attr("flatten_paths")().cast<py::list>();
|
||||
REQUIRE(ps.size() == 2);
|
||||
py::array pts = ps[1].attr("points")().cast<py::array>(); // pathB: (1,1,0),(2,1,0),(2,2,0)
|
||||
CHECK(pts.dtype().kind() == 'i');
|
||||
CHECK(pts.itemsize() == 8);
|
||||
CHECK(pts.shape(0) == 3);
|
||||
CHECK(pts.shape(1) == 3);
|
||||
CHECK_FALSE(pts.writeable());
|
||||
auto r = pts.cast<py::array_t<coord_t>>().unchecked<2>();
|
||||
CHECK(r(0, 0) == 1); CHECK(r(1, 0) == 2); CHECK(r(2, 1) == 2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raw Print-graph spine (orca.host): LayerRegion / Layer / PrintObject / Print,
|
||||
// read side. LayerRegion/Layer ctors are protected (friend class PrintObject),
|
||||
// so the tests use tiny derived structs -- the pattern TestLayerRegion above
|
||||
// already establishes; TestLayer is its Layer counterpart.
|
||||
// ---------------------------------------------------------------------------
|
||||
namespace {
|
||||
struct TestLayer : Slic3r::Layer {
|
||||
// id=0, no owning PrintObject, height/print_z/slice_z suitable for assertions.
|
||||
TestLayer() : Slic3r::Layer(0, nullptr, 0.2, 0.45, 0.35) {}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("orca.host graph classes: LayerRegion/Layer raw traversal; Print/PrintObject registered", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
|
||||
for (const char* name : { "LayerRegion", "Layer", "PrintObject", "Print" })
|
||||
CHECK(py::hasattr(host, name));
|
||||
// Members needing a live Print are verified by registration only (slic3rutils
|
||||
// cannot build a Print; the fff_print C++ suite covers live-graph behavior).
|
||||
for (const char* name : { "layers", "support_layers", "model_object", "id",
|
||||
"bounding_box", "trafo", "config_value", "config_keys" })
|
||||
CHECK(py::hasattr(host.attr("PrintObject"), name));
|
||||
for (const char* name : { "objects", "model", "config_value", "config_keys", "canceled" })
|
||||
CHECK(py::hasattr(host.attr("Print"), name));
|
||||
|
||||
// Raw LayerRegion traversal over a hand-built region.
|
||||
TestLayerRegion region;
|
||||
region.slices.surfaces.emplace_back(Slic3r::Surface(Slic3r::stInternal));
|
||||
build_nested_perimeters(region); // helper defined earlier in this file
|
||||
py::object lr = py::cast(static_cast<Slic3r::LayerRegion*>(®ion),
|
||||
py::return_value_policy::reference);
|
||||
CHECK(lr.attr("slices").attr("size")().cast<size_t>() == 1);
|
||||
CHECK(lr.attr("slices").attr("surfaces").cast<py::list>().size() == 1);
|
||||
CHECK(lr.attr("perimeters").attr("flatten_paths")().cast<py::list>().size() == 2);
|
||||
CHECK(lr.attr("fills").attr("size")().cast<size_t>() == 0);
|
||||
CHECK(lr.attr("layer")().is_none()); // hand-built region has no owning layer
|
||||
|
||||
// Raw Layer scalars + empty traversals on a hand-built layer.
|
||||
TestLayer layer;
|
||||
py::object ly = py::cast(static_cast<Slic3r::Layer*>(&layer),
|
||||
py::return_value_policy::reference);
|
||||
CHECK_THAT(ly.attr("print_z").cast<double>(), WithinRel(0.45, 1e-9));
|
||||
CHECK_THAT(ly.attr("slice_z").cast<double>(), WithinRel(0.35, 1e-9));
|
||||
CHECK_THAT(ly.attr("height").cast<double>(), WithinRel(0.2, 1e-9));
|
||||
CHECK(ly.attr("regions")().cast<py::list>().size() == 0);
|
||||
CHECK(ly.attr("lslices")().cast<py::list>().size() == 0);
|
||||
CHECK(ly.attr("upper_layer").is_none());
|
||||
CHECK(ly.attr("lower_layer").is_none());
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host: plugin-only mutators are gone; class-API editing works", "[slicing_pipeline]") {
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
|
||||
// The three plugin-only mutators were removed in the raw-API realignment.
|
||||
CHECK_FALSE(py::hasattr(host.attr("LayerRegion"), "set_slices"));
|
||||
CHECK_FALSE(py::hasattr(host.attr("LayerRegion"), "set_fill_surfaces"));
|
||||
CHECK_FALSE(py::hasattr(host.attr("Layer"), "set_lslices"));
|
||||
// The faithful surface is present.
|
||||
CHECK(py::hasattr(host.attr("SurfaceCollection"), "set"));
|
||||
CHECK(py::hasattr(host.attr("Layer"), "make_slices"));
|
||||
|
||||
// clear() via the collection on a hand-built region (null owning layer is null-safe).
|
||||
TestLayerRegion region;
|
||||
region.slices.surfaces.emplace_back(Slic3r::Surface(Slic3r::stInternal));
|
||||
py::object lr = py::cast(static_cast<Slic3r::LayerRegion*>(®ion), py::return_value_policy::reference);
|
||||
lr.attr("slices").attr("clear")();
|
||||
CHECK(region.slices.surfaces.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host: SurfaceCollection.set mutates geometry; lslices via make_slices", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
bool have_numpy = false;
|
||||
try { py::module_::import("numpy"); have_numpy = true; }
|
||||
catch (const py::error_already_set&) { have_numpy = false; }
|
||||
if (!have_numpy) SKIP("numpy unavailable in unit-test interpreter");
|
||||
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
py::module_ np = py::module_::import("numpy");
|
||||
py::object i64 = np.attr("int64");
|
||||
py::object ST = host.attr("SurfaceType");
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
auto arr = [&](std::initializer_list<std::pair<coord_t,coord_t>> pts) {
|
||||
py::list rows; for (auto& p : pts) rows.append(py::make_tuple(p.first, p.second));
|
||||
return np.attr("array")(rows, py::arg("dtype") = i64);
|
||||
};
|
||||
|
||||
// Build an ExPolygon from a CW ndarray; the ctor normalizes to CCW.
|
||||
py::object ex = host.attr("ExPolygon")(arr({ {0,0}, {0,s}, {s,s}, {s,0} }));
|
||||
CHECK(ex.attr("contour").attr("is_counter_clockwise")().cast<bool>());
|
||||
|
||||
TestLayerRegion region;
|
||||
py::object lr = py::cast(static_cast<Slic3r::LayerRegion*>(®ion), py::return_value_policy::reference);
|
||||
py::list expolys; expolys.append(ex);
|
||||
lr.attr("slices").attr("set")(expolys, ST.attr("stInternalSolid"));
|
||||
REQUIRE(region.slices.surfaces.size() == 1);
|
||||
const Slic3r::Surface& out = region.slices.surfaces.front();
|
||||
CHECK(out.surface_type == Slic3r::stInternalSolid);
|
||||
CHECK_THAT(out.expolygon.area(), WithinRel((double) s * (double) s, 1e-9));
|
||||
// Read geometry back through the class API.
|
||||
py::array c = lr.attr("slices").attr("surfaces").cast<py::list>()[0]
|
||||
.attr("expolygon").attr("contour").attr("as_array")().cast<py::array>();
|
||||
CHECK(c.shape(0) == 4);
|
||||
|
||||
// lslices are derived: make_slices() re-derives them + refreshes the bbox cache.
|
||||
TestLayer layer;
|
||||
py::object ly = py::cast(static_cast<Slic3r::Layer*>(&layer), py::return_value_policy::reference);
|
||||
// (A hand-built layer has no regions, so make_slices() yields empty lslices — still null-safe.)
|
||||
ly.attr("make_slices")();
|
||||
CHECK(layer.lslices_bboxes.size() == layer.lslices.size());
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host ExPolygon in-place transforms + SurfaceCollection.append (sample ops)", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
py::object host = py::module_::import("orca").attr("host");
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
auto make_square = [&]() {
|
||||
py::object P = host.attr("Polygon")();
|
||||
P.attr("append")(host.attr("Point")(0, 0));
|
||||
P.attr("append")(host.attr("Point")(s, 0));
|
||||
P.attr("append")(host.attr("Point")(s, s));
|
||||
P.attr("append")(host.attr("Point")(0, s));
|
||||
return host.attr("ExPolygon")(P);
|
||||
};
|
||||
const double area0 = (double) s * (double) s;
|
||||
|
||||
// rotate about the square's center preserves area
|
||||
py::object ex = make_square();
|
||||
py::object center = host.attr("Point")(s / 2, s / 2);
|
||||
ex.attr("rotate")(py::float_(1.5707963267948966), center); // pi/2
|
||||
CHECK_THAT(ex.attr("area")().cast<double>(), WithinRel(area0, 1e-6));
|
||||
|
||||
// uniform scale by 2 quadruples area (scale is about the origin)
|
||||
py::object ex2 = make_square();
|
||||
ex2.attr("scale")(py::float_(2.0));
|
||||
CHECK_THAT(ex2.attr("area")().cast<double>(), WithinRel(4.0 * area0, 1e-6));
|
||||
|
||||
// translate preserves area
|
||||
py::object ex3 = make_square();
|
||||
ex3.attr("translate")(py::float_(1000.0), py::float_(-500.0));
|
||||
CHECK_THAT(ex3.attr("area")().cast<double>(), WithinRel(area0, 1e-6));
|
||||
|
||||
// SurfaceCollection.append accumulates surfaces of a second type (the sample write-back path)
|
||||
Slic3r::SurfaceCollection coll;
|
||||
py::object cv = py::cast(&coll, py::return_value_policy::reference);
|
||||
py::list g1; g1.append(make_square());
|
||||
cv.attr("set")(g1, host.attr("SurfaceType").attr("stInternalSolid"));
|
||||
py::list g2; g2.append(make_square());
|
||||
cv.attr("append")(g2, host.attr("SurfaceType").attr("stTop"));
|
||||
REQUIRE(coll.surfaces.size() == 2);
|
||||
CHECK(coll.surfaces[0].surface_type == Slic3r::stInternalSolid);
|
||||
CHECK(coll.surfaces[1].surface_type == Slic3r::stTop);
|
||||
}
|
||||
|
||||
TEST_CASE("orca.host: in-place edit of surface.expolygon through a live collection persists to C++", "[slicing_pipeline]") {
|
||||
using Catch::Matchers::WithinRel;
|
||||
ensure_python_initialized();
|
||||
import_orca_module();
|
||||
py::gil_scoped_acquire gil;
|
||||
|
||||
const coord_t s = (coord_t) scale_(10.0);
|
||||
// Live LayerRegion holding one surface (a 10mm square at the origin).
|
||||
TestLayerRegion region;
|
||||
Slic3r::ExPolygon sq;
|
||||
sq.contour.points = { Slic3r::Point(0, 0), Slic3r::Point(s, 0),
|
||||
Slic3r::Point(s, s), Slic3r::Point(0, s) };
|
||||
region.slices.surfaces.emplace_back(Slic3r::Surface(Slic3r::stInternal, sq));
|
||||
py::object lr = py::cast(static_cast<Slic3r::LayerRegion*>(®ion),
|
||||
py::return_value_policy::reference);
|
||||
|
||||
// Twistify's path: get the Surface through the live collection, mutate its expolygon in place.
|
||||
py::object surf = lr.attr("slices").attr("surfaces").cast<py::list>()[0];
|
||||
surf.attr("expolygon").attr("translate")(py::float_(1000.0), py::float_(0.0));
|
||||
|
||||
// The C++-side surface geometry reflects the Python in-place edit (proves the live ref).
|
||||
const Slic3r::Surface& out = region.slices.surfaces.front();
|
||||
CHECK(out.expolygon.contour.points[0].x() == 1000); // was 0
|
||||
CHECK(out.expolygon.contour.points[0].y() == 0);
|
||||
CHECK_THAT(out.expolygon.area(), WithinRel((double) s * (double) s, 1e-9)); // translate preserves area
|
||||
}
|
||||
153
tests/slic3rutils/test_slicing_pipeline_config.cpp
Normal file
153
tests/slic3rutils/test_slicing_pipeline_config.cpp
Normal file
@@ -0,0 +1,153 @@
|
||||
#include <catch2/catch_all.hpp>
|
||||
|
||||
#include <libslic3r/Utils.hpp>
|
||||
#include <slic3r/plugin/PluginConfig.hpp>
|
||||
#include <slic3r/plugin/PluginManager.hpp>
|
||||
#include <slic3r/plugin/PythonInterpreter.hpp>
|
||||
#include <slic3r/plugin/PythonPluginInterface.hpp>
|
||||
|
||||
#include "fff_print/test_helpers.hpp"
|
||||
#include "plugin_test_utils.hpp"
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <pybind11/embed.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using namespace Slic3r;
|
||||
using namespace Slic3r::Test;
|
||||
namespace fs = boost::filesystem;
|
||||
using json = nlohmann::json;
|
||||
|
||||
// End-to-end coverage of a slicing-pipeline capability reading its own config: the loader seeds the
|
||||
// store from the capability's get_default_config() hook, and the real dispatch
|
||||
// (execute_capabilities_from_refs -> hook -> GIL -> trampoline) lets the plugin read back whatever
|
||||
// the host has stored, through self.get_config(). A break anywhere in that chain makes plugins
|
||||
// silently run on their built-in defaults, which is invisible to the plugin author (Twistify
|
||||
// incident, 2026-07-17).
|
||||
//
|
||||
// Note this is deliberately NOT ctx.config_value(): that reads the slicer's print config, not the
|
||||
// plugin's own config.
|
||||
|
||||
namespace {
|
||||
|
||||
struct ScopedPluginManager
|
||||
{
|
||||
bool initialized = false;
|
||||
|
||||
ScopedPluginManager() { initialized = PluginManager::instance().initialize(); }
|
||||
~ScopedPluginManager()
|
||||
{
|
||||
PluginManager::instance().shutdown();
|
||||
PythonInterpreter::instance().shutdown();
|
||||
}
|
||||
};
|
||||
|
||||
const char* const CONFIG_PROBE_SOURCE = R"PY(# /// script
|
||||
# requires-python = ">=3.12"
|
||||
#
|
||||
# [tool.orcaslicer.plugin]
|
||||
# name = "Config Probe"
|
||||
# description = "Echoes its own config back to the test"
|
||||
# author = "OrcaSlicer"
|
||||
# version = "1.0"
|
||||
# type = "slicing-pipeline"
|
||||
# ///
|
||||
import json
|
||||
|
||||
import orca
|
||||
|
||||
class ConfigEcho(orca.slicing.SlicingPipelineCapabilityBase):
|
||||
def get_name(self):
|
||||
return "ConfigEcho"
|
||||
|
||||
def get_default_config(self):
|
||||
return {"alpha": "1.25", "beta": "hello"}
|
||||
|
||||
def execute(self, ctx):
|
||||
if ctx.step != orca.slicing.Step.posSlice or ctx.object is None:
|
||||
return orca.ExecutionResult.success()
|
||||
try:
|
||||
text = repr(sorted(json.loads(self.get_config()).items()))
|
||||
except Exception as e: # what plugins' defaults-fallback code swallows silently
|
||||
text = "config-error: " + repr(e)
|
||||
orca._probe_config = text # read back by the test through pybind
|
||||
return orca.ExecutionResult.success("config probed")
|
||||
|
||||
@orca.plugin
|
||||
class ConfigProbePackage(orca.base):
|
||||
def register_capabilities(self):
|
||||
orca.register_capability(ConfigEcho)
|
||||
)PY";
|
||||
|
||||
fs::path write_plugin(const std::string& stem, const std::string& source)
|
||||
{
|
||||
const fs::path plugin_dir = fs::path(get_orca_plugins_dir()) / stem;
|
||||
fs::create_directories(plugin_dir);
|
||||
|
||||
std::ofstream out((plugin_dir / (stem + ".py")).string(), std::ios::binary);
|
||||
out << source;
|
||||
out.close();
|
||||
|
||||
return plugin_dir;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("slicing-pipeline dispatch delivers the stored config to self.get_config()", "[slicing_pipeline][PluginConfig][Python]")
|
||||
{
|
||||
ScopedPluginManager plugin_system;
|
||||
if (!plugin_system.initialized)
|
||||
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
|
||||
|
||||
ScopedDataDir data_dir_guard("pipeline-config");
|
||||
write_plugin("ConfigProbe", CONFIG_PROBE_SOURCE);
|
||||
|
||||
PluginManager& manager = PluginManager::instance();
|
||||
manager.get_config().load(); // reset the singleton's store against the empty temp data dir
|
||||
manager.discover_plugins(/*async=*/false, /*clear=*/true);
|
||||
|
||||
std::string error;
|
||||
manager.load_plugin("ConfigProbe", /*skip_deps=*/true, {});
|
||||
REQUIRE(manager.wait_for_plugin_load("ConfigProbe", std::chrono::seconds(120), error));
|
||||
INFO("load error: " << error);
|
||||
REQUIRE(manager.is_plugin_loaded("ConfigProbe"));
|
||||
|
||||
const PluginCapabilityId id{PluginCapabilityType::SlicingPipeline, "ConfigEcho", "ConfigProbe"};
|
||||
|
||||
// Loading seeds the store from the capability's get_default_config() hook, so a plugin has a
|
||||
// config before anyone has opened the Config tab.
|
||||
const auto seeded = manager.get_config().get_config(id);
|
||||
REQUIRE(seeded);
|
||||
CHECK(seeded->config == json({{"alpha", "1.25"}, {"beta", "hello"}}));
|
||||
|
||||
// What editing the config in the Config tab does: the value the plugin must actually run on.
|
||||
REQUIRE(manager.get_config().store_capability_config(id, json({{"alpha", "9.5"}, {"beta", "hello"}})));
|
||||
|
||||
// Slice with the capability selected, exactly as a preset would reference it.
|
||||
Print print;
|
||||
Model model;
|
||||
auto config = DynamicPrintConfig::full_print_config();
|
||||
config.set_key_value("slicing_pipeline_plugin", new ConfigOptionStrings({"ConfigEcho"}));
|
||||
config.set_key_value("plugins", new ConfigOptionStrings({"ConfigProbe;;ConfigEcho"}));
|
||||
init_print({cube(20)}, print, model, config);
|
||||
print.process();
|
||||
|
||||
std::string observed = "<capability never executed>";
|
||||
{
|
||||
PythonGILState gil;
|
||||
REQUIRE(static_cast<bool>(gil));
|
||||
pybind11::module_ orca = pybind11::module_::import("orca");
|
||||
if (pybind11::hasattr(orca, "_probe_config"))
|
||||
observed = orca.attr("_probe_config").cast<std::string>();
|
||||
}
|
||||
INFO("config observed by Python: " << observed);
|
||||
// The edited value arrived, not the seeded default: the host's store is what reaches the plugin.
|
||||
CHECK(observed.find("'alpha', '9.5'") != std::string::npos);
|
||||
CHECK(observed.find("'beta', 'hello'") != std::string::npos);
|
||||
CHECK(observed.find("1.25") == std::string::npos);
|
||||
|
||||
manager.unload_plugin("ConfigProbe");
|
||||
}
|
||||
Reference in New Issue
Block a user