Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

u1c-kernel

Bambu 3mf → Snapmaker U1 process parameter migration C++ kernel (u1c) — a pure kernel repo: source + tracked rules assets + vendored third-party code (the U1 template and the bilingual label table are consumer-supplied; see the asset contract below). It is designed for host repos such as snapmaker-3mf-agent to integrate by mounting it as a submodule (add_subdirectory); standalone build for self-testing is also supported.

This is not a format converter: the U1 official template provides identity and hardware fields, and the kernel migrates only the process whitelist + geometry + filament. The 221 whitelist fields (action: copy / remap_enum / enum_guard / fix_zero / fix_negative / collapse_then_copy / skip) are defined in rules/u1_craft_migration.yaml — this repo's core asset.

Four Core Capabilities

  • STL → 3MF assembly: u1c::conv::stl_to_3mf (manifest v2 tree protocol; in-memory bytes variant stl_to_3mf_buffer);
  • In-memory mesh → 3MF: mesh_to_3mf / mesh_to_3mf_buffer (direct pass-through without touching disk; MeshRequest resource table + SceneNode scene graph);
  • GLB → 3MF assembly: glb_to_3mf / glb_to_3mf_buffer (GlbRequest bytes + options, glTF 2.0 binary, pure in-memory in and out, naturally suited to wasm);
  • 3MF → 3MF migration: threemf_to_3mf / threemf_to_3mf_buffer (single entry point with dual modes — project 3MF process migration / model-only 3MF assembly; the buffer variant is bytes in and out: source via ThreemfRequest.source_bytes, artifact in ThreemfBuffer.data; threemf_to_document returns uncompressed entries without an output archive; probe_3mf probes the source form) + session engine u1c::engine (12 session functions).

See the header comments under include/u1c/ for detailed protocols and boundaries. Bridging (pyd / CLI / DLL / embind), host examples, e2e and golden replay, and the WASM artifact pipeline live in the host repo snapmaker-3mf-agent.

In-Memory GLB and 3MF Interfaces

Both interfaces accept binary input and a JSON options object, returning a report and the generated 3MF bytes:

struct GlbRequest {
  std::vector<uint8_t> glb_bytes;
  Json options = Json::object();
};

struct ThreemfRequest {
  std::vector<uint8_t> source_bytes;
  Json options = Json::object();
};

struct ThreemfBuffer {
  Json report;
  std::vector<uint8_t> data;
};

Result<ThreemfBuffer> glb_to_3mf_buffer(const GlbRequest& req);
Result<ThreemfBuffer> threemf_to_3mf_buffer(const ThreemfRequest& req);

The types and functions above belong to u1c::conv. Call u1c::init first. Native builds expose the same kernel on Windows, macOS and Linux; see BUILD.md for static/shared-library builds and CTest commands. An empty options object uses defaults. GLB options retain their existing flat settings and color/painting options. With paint_textures: true (the default), textured meshes are adaptively subdivided where the image varies, down to approximately one texel per triangle edge. Shared edges within a mesh are split consistently across UV and material seams. UVs and vertex colors are interpolated; each resulting triangle samples its texture at the centroid. All GLB models select distinct colors in first-seen mesh/primitive/triangle traversal order, whether or not refinement occurs. Color coverage area does not affect selection.

GLB conversion returns ErrorCode::GlbColorLimitExceeded when more than 64 distinct RGB colors are sampled, before limiting the palette or applying color overrides. The count uses per-triangle colors after conversion to 8-bit RGB, including material and vertex colors and enabled texture sampling. No 3MF is written on this error; an existing output file is left unchanged. C++ consumers can branch on error().code(); error().kind() classifies this failure as ErrKind::Parse. Adapters that expose only diagnostic text must forward the code to let a frontend distinguish this failure.

Texture painting uses nearest-neighbor sampling at each refined triangle's UV centroid, preserving source texel colors without interpolation blends. Adaptive texture subdivision is unchanged. Material factors and vertex colors still multiply the sampled color and may change the final RGB.

max_colors caps the shared palette (1–64, default 64). Exact duplicate colors share an entry; similar colors are not merged by a color-difference threshold. Keep all distinct colors up to the cap; above it, retain the first max_colors entries in the order above and map remaining colors to the nearest retained color (CIE76). For a four-color limit, pass {"max_colors": 4}. GLB filament assembly uses the same selection policy; other conversion formats retain their existing clustering behavior. Refinement allows at most 16 passes per mesh and 500,000 additional triangles across decoded meshes; reaching a limit adds a warning that some texture detail may be lost. paint_textures: false disables texture sampling and refinement. The file, buffer and DLL entry points share this behavior without a signature change.

3MF options accept:

  • template_path, rules_path: optional asset paths;
  • machine_id, process_preset: optional machine and process selections;
  • process_config: optional effective host process settings, applied over the system preset before source migration. Recognized process fields in rules/orca_override_fields.json are accepted as-is without strict value validation; unknown fields, selection keys, and null entries are ignored and omitted from report.process_config_keys, which lists accepted fields. The host must retain unsupported fields and rebuild local preset identity and inheritance. Source values selected by conversion_mode override this baseline only when valid; flat process overrides still take final precedence;
  • filament_overrides: source slot index strings mapped to filament categories (project migration only). Indices must identify existing physical source slots; normalized duplicate indices are rejected. Values must be category strings listed in the rules table's filament_subtypes values (case-sensitive);
  • filament_presets: an array of output-slot preset IDs. Generic models accept one explicit preset ID. When omitted, assembly defaults to Generic PLA. If the snapshot only provides nozzle-qualified variants, it selects the one compatible with the target printer;
  • conversion_mode: process migration scope for project 3MFs; filaments always map to system presets, and the report echoes the mode. No effect on generic models:
    • system (default): use the target process baseline, migrate no source values;
    • modified: migrate whitelisted keys listed in the source's different_settings_to_system;
    • full: migrate every whitelisted key the source defines;
  • migration aliases apply when the source lacks the target spelling. For example, sparse_infill_anchor_max can supply infill_anchor_max;
  • flat process keys such as wall_loops and layer_height, validated by rules/orca_override_fields.json. Values use their on-disk types, usually strings; numeric values are not automatically converted to strings.

Numeric process overrides require finite strings, integer syntax for integer fields, and values within the field table's inclusive min/max bounds. Percent suffixes are accepted only for percent-capable fields. Vector elements and per-node properties use the same validation. Invalid overrides return InvalidArgument instead of being skipped.

During process migration, source values are checked against the field table's types, enum values and inclusive min/max bounds. Invalid types, failed numeric parsing, fractional integers, non-finite numbers and illegal enums are skipped. The target baseline is preserved; craft.diffs records action: "skip", the original source and baseline values, and the reason in note. The reason also appears in warnings. Explicit enum mappings are validated against the target enum values; unknown enums do not use a default mapping. Boolean values accept JSON booleans, numeric 0/1 and strings "0"/"1". Percent suffixes are accepted only for percent-capable fields. Legacy arrays are checked element by element before collapsing to their first value; empty or invalid arrays are skipped. This check applies to migrated source values, not explicit flat overrides. Hosts supplying the field table must refresh its bounds when parameter definitions change.

Flow-dependent process fields follow the target's effective process_flow_support declaration. A missing or empty declaration defaults to standard flow. With one effective mode, migration writes the source value even when the target field contains extra entries. With multiple declared modes, migration keeps the target baseline for that field. Fields that store per-nozzle values, tool indices, or calibration curves require field-specific handling to preserve their structure.

For example:

u1c::conv::ThreemfRequest req;
req.source_bytes = source_bytes;
req.options = {{"machine_id", "Snapmaker U1 (0.4 nozzle)"},
               {"filament_presets", {"Generic PLA"}},
               {"wall_loops", "3"}, {"layer_height", "0.16"}};
auto result = u1c::conv::threemf_to_3mf_buffer(req);
// On success: result.value().report and result.value().data.

3MF input still dispatches automatically between project migration and generic model assembly. Generic models also accept the flat assembly slots nozzle and filament_preset; project migration uses machine_id and filament_presets instead. Do not specify both forms for the same selection. Both interfaces reject non-object options and source/output/source_bytes keys inside options. The memory interface also rejects empty source bytes. It writes no artifact to disk; the report has output: "<memory>" and no source key.

Project migration carries Metadata/custom_gcode_per_layer.xml verbatim, warning on template and custom G-code entries. Entries on plates the project no longer has are dropped with a warning, and files with no entries are not carried. It warns when paint_color references a filament beyond the output slots, and rejects NaN or infinite vertices and transforms with a Parse error.

Variable layer height profiles, brim ears and cut information are carried when well formed; heights outside the printer's limits warn. Height range modifiers keep only options the target supports. Malformed files are dropped with a warning.

filament_type comes from the selected preset. Automatic mappings that change the base material, reinforcement or support role warn; user selections do not. Flow-variant filament options are written as per-filament segments described by filament_flow_step_size, so these arrays can be longer than the slot count.

An Application value Snapmaker Orca does not treat as a project (for example Creality Print) is replaced with the template's, and the report events record the change. BambuStudio- and Snapmaker_Orca- values are kept.

Colour mixing becomes Snapmaker virtual filaments: Bambu mixed slots leave the physical list, Creality rows are rebuilt, and object, part, paint and layer G-code numbers follow, as do per-object feature filament options. filament_overrides keep source slot indices, while filament_presets lists physical slots only.

The file entry follows the GLB interface and shares the memory entry's options:

Result<Json> threemf_to_3mf(const std::string& source_path,
                          const std::string& out_path = "",
                          const Json& options = Json::object());

An empty output path uses converted_u1.3mf. C++ callers of the former request-based file interface pass paths as arguments, move selections into options, and flatten overrides into it. There is no separate public file request type. The DLL file-conversion JSON contract is unchanged.

Uncompressed 3MF Documents

threemf_to_document runs the same conversion as the file and ZIP-buffer APIs, but returns owned, uncompressed entries without packing or writing an output archive. Both project migration and generic-model assembly are supported.

// After u1c::init(asset_root, presets_dir):
auto result = u1c::conv::threemf_to_document(
    source_path, u1c::Json{{"conversion_mode", "modified"}});
if (!result) {
  return u1c::fail(result.error());
}
auto document = std::move(result.value());
for (const auto& entry : document.entries) {
  // entry.path is package-relative UTF-8; entry.data may contain NUL bytes.
  consume_entry(entry.path, entry.data.data(), entry.data.size());
}

The document interface accepts a source file path and options:

Result<ThreemfDocument> threemf_to_document(const std::string& source_path,
                                          const Json& options = Json::object());

ThreemfDocument contains Json report and ThreemfEntries entries. Each ThreemfEntry owns std::string path and binary-safe std::string data; the carrier is declared in include/u1c/threemf_document.hpp without a JSON dependency. Entry order and bytes match the corresponding ZIP output, including its existing path filtering. The report uses output: "<memory>" and includes the source path in source. Existing options validation, carry lists, warnings, and events are unchanged. Keep the document alive while a host parser uses views into its entries. The source ZIP still needs decompression and the host still needs to parse model/configuration content.

In-memory project entry conversion

Call u1c::init and pass the source entry views to prepare_entry_conversion(ProjectInput, options). Supply raw project settings, optional model settings, and the root model's package-relative path and metadata XML. Paths use the package spelling without a leading slash. The source views must remain valid through preparation only. Preparation does not read model geometry; the host completes placement with finish_entry_geometry after parsing its models.

The plan owns the preset selections, filament numbering, and plate IDs. Geometry completion adds placement offsets in a new plan. The completed plan can be shared between readers. Each conversion takes the source bytes from the same project and produces the requested edit on demand.

Function Source bytes
convert_project_settings_with_process(source, plan) Metadata/project_settings.config
convert_model_settings(source, plan) Metadata/model_settings.config, when present

convert_model_settings returns Keep when no object or part filament reference changes. Identity numbering bypasses XML parsing; changed numbering rewrites only references present in the mapping. Default, unknown, and unchanged numbers retain their values. Existing plate filament_maps values are preserved, not rebuilt. Unavailable Creality mixed rows are removed: object/part extruders become zero, feature overrides are removed, and later virtual IDs move down. References no longer fall back to a surviving component. Full-project migration follows the same model-settings rules. When references change, XML serialization may change formatting; otherwise the original entry bytes are preserved.

Pass a saved process baseline as process_config in the preparation options along with the target machine_id and system process_preset. In modified mode, valid source changes marked in different_settings_to_system take precedence over this baseline according to the migration rules. convert_project_settings_with_process returns the normal edit plus the process keys accepted from the baseline, migrated from the source, or applied as explicit process overrides. It also returns serialized conversion details for the target machine, filaments, and process migration. Each entry's warnings remain on its edit. Hosts can use the keys to preserve the converted values while restoring local preset identity, inheritance, and options outside the kernel schema.

finish_entry_geometry also returns filament_remap when numbering changes. Hosts must apply this one-based map to native paint, height-range overrides, and layer commands after parsing. Zero means no explicit filament; remove feature overrides and tool changes targeting removed rows. Do not remap object/part settings twice: convert_model_settings already handles those references. The result layout changed; rebuild the host and shared library together.

Other metadata, including height ranges, per-layer G-code, layer height profiles, brim ear points, and cut information, is read and parsed directly by the host. The entry API does not translate range options, remap per-layer filament numbers, filter stale plates, or validate these attachments. Independent whole-document conversion retains its metadata migration and validation.

EntryEdit carries warnings and an operation. Keep preserves the original bytes; Replace owns the complete uncompressed replacement. Apply related settings edits from the same plan together. Callers own archive I/O and decide which stale slicing data to discard.

Streaming project hosts

Provide root metadata XML instead of full model bytes. Entry preparation always leaves geometry analysis to the host. The host may stop its root header scan at the first resources/build element; metadata must precede geometry. Use the independent whole-document APIs when the kernel must read and rewrite model XML.

Stream model entries through the host parser. Use entry_application(plan) before producer-dependent handling. Preserve triangle paint_color attributes unchanged in the streaming host path. Geometry parsing and validation remain with the host. Compute exact world-space XY minima/maxima and maximum Z from already-loaded vertices, including all component and instance transforms. Supply InstanceBounds in root build-item order, using source object IDs; use empty bounds for absent geometry.

finish_entry_geometry(bounds, plan) returns a new immutable plan, per-item XY offsets, and geometry warnings. It uses the same plate membership, clustering, clamping, and off-plate policy as the XML path. Apply offsets to host instances, then use the completed plan for project settings so wipe-tower coordinates match. Project settings conversion rejects a plan whose geometry is still pending. Completion does not mutate the input plan. This path retains configuration and geometry summaries, not complete model XML or a second vertex array.

Dynamic-loading C++ hosts

Include u1c/threemf_engine.hpp and resolve the u1c_make_threemf_engine factory. The returned ThreemfEngine exposes version, initialization, probing, file conversion, document conversion, and entry conversion. Call its init before conversion. The instance is DLL-owned and must not be deleted.

ThreemfEngine::threemf_to_document accepts a source file path plus serialized JSON options (empty string uses defaults). It returns Result<ThreemfDocumentResult> with report_json and owned entries. Malformed JSON options return Parse; conversion failures preserve their error kind and message. No vendored JSON value crosses the document interface.

The factory uses the current ThreemfEngine and ProjectInput layouts without ABI version negotiation. Rebuild and deploy hosts and libraries together.

The ThreemfEngine entry methods are prepare_entry_conversion, convert_model_settings, probe_project, convert_project_settings_with_process, entry_application, and finish_entry_geometry. The preparation options are serialized JSON (an empty string uses defaults). The methods return the same typed plans, edits, warnings, and errors as the in-memory kernel API above. ThreemfEngine::probe_project takes the root model and project settings as uncompressed byte views so hosts can reuse their existing archive readers. It needs no initialization and shares the source classifier used by probe_3mf.

Rebuild and deploy the host and DLL together. They must use compatible tools, standard libraries, CRTs, and build settings. Keep the module loaded until all returned values, including plans and edits, are destroyed.

The document import design and its Chinese translation describe the whole-document handoff.

Asset Contract and init

u1c::init(asset_root, presets_dir = "") (include/u1c/u1c.hpp):

  • asset_root: the asset root, containing rules/ and template/ (shipped with this repo);
  • presets_dir: the preset snapshot directory (parent directory of machine/filament/process), provided by the consumer — this repo never commits presets — empty = default <asset_root>/presets/snapmaker (for standalone self-testing, just place the snapshot temporarily at that path; it is already ignored by .gitignore); non-empty must be an absolute path; idempotent, lazy loading; missing assets error out at first use.

Asset authority is three-way: rules/u1_craft_migration.yaml and rules/orca_override_fields.json are authoritative in this repo; rules/orca_field_labels.json and template/ are consumer-supplied like presets (never committed here; authoritative copies live at snapmaker-3mf-agent:assets/u1c/, and the host syncs them into this tree for local runs — tools/sync_internal_assets.py in the host repo); the presets/ snapshot is likewise maintained by each host repo.

Automatic Filament Mapping

Project migration selects a preset compatible with the target machine and nozzle in this order: the same preset name across all compatible brands, Snapmaker with the same material name, the registered Snapmaker base family for the category, the registered Generic base family, then Generic PLA. Same-preset matching preserves the brand, ignores case and machine qualifiers after @, and reports tier 1. When neither exact name matches, a registered filament_dynamic.material_aliases entry selects a compatible grade at tier 1, checking Snapmaker before Generic. PLA Silk+ maps to PLA Silk, and Hyper PLA maps to PLA High Speed. Category overrides skip the name and alias stages. PCTG has its own category and Generic base family. Unknown subtypes retain their names for exact matching; unknown categories skip the two category stages. An unavailable compatible Generic PLA is an error.

filament_dynamic.category_presets and generic_category_presets in the migration rules register base families explicitly. Special grades are never arbitrary category fallbacks. The previous subtype_presets replacements are no longer used. Explicitly selected presets must also be compatible; they are not silently replaced. Each report's filament_slots includes source_type, normalized source_name, selection and mapping_tier (1–4 automatic, 0 manual). Fallbacks add warnings. Automatic substitutions report a lost support role or flame-retardant (FR) grade when the selected preset lacks that property.

Mixed Filament Gradients

Migration converts recognized Bambu, Creality and Snapmaker gradients to fixed Ratio mode. Bambu slots retain filament_mixed_sublayer_ratios (equal shares when missing); definition rows retain their mix percentage or component weights. Height ranges, curves and per-part gradient behavior are ignored with a warning. Virtual filament numbering and model references remain intact. Unrecognized mixed filament handling is unchanged.

Standalone Build and Self-Testing

# Borrow consumer-supplied assets from the host repo (never committed here):
# presets/ from the host root, field_labels + template from the host assets dir
Copy-Item -Recurse ..\snapmaker-3mf-agent\presets presets
Copy-Item ..\snapmaker-3mf-agent\assets\u1c\rules\orca_field_labels.json rules\
Copy-Item -Recurse ..\snapmaker-3mf-agent\assets\u1c\template template

cmake -S . -B build -A x64
cmake --build build --config Release

bin\u1c_mesh_tests.exe
bin\u1c_glb_tests.exe
bin\u1c_stl_tests.exe
bin\u1c_threemf_tests.exe
bin\u1c_tests.exe machines   # force asset loading (rules/presets/template)

Feature toggles U1C_FEATURE_{STL,MESH,GLB,CONVERT} (four feature units, independently configurable and independently publishable) and U1C_BUILD_TESTS are detailed in BUILD.md. Golden replay and the four-bridge e2e are driven by the host repo; this repo's test exes form the white-box reference layer.

Mounted Integration (submodule)

Host repo mounting (see the snapmaker-3mf-agent root CMakeLists):

set(U1C_KERNEL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/u1c-kernel" CACHE PATH "")
add_subdirectory("${U1C_KERNEL_DIR}")
  • The kernel carries its own project(u1c VERSION x.y.z); the version is visible to the mounting side via the cache variable U1C_KERNEL_VERSION;
  • Feature toggles are plain option caches: to change a default, the host must set(... CACHE BOOL ... FORCE) before add_subdirectory;
  • When mounted, the kernel sets no output directory variables — build products land at the location agreed by the mounting side (directory properties are evaluated at target-creation time);
  • Under Emscripten builds the kernel tree automatically adds -fexceptions (exceptions cross TU boundaries; consumers rely on C++ exception support);
  • C++ host integration: take include/u1c/ + the kernel static library + third_party/nlohmann/json.hpp; see BUILD.md for link order;
  • Consumers should link the aggregate target projectcore::engine (the full closure under the current feature switches) instead of naming the ten internal targets; for dynamic-loading hosts the repo also builds the C ABI shim 3mf_engine.dll (bindings/cabi, toggle U1C_BUILD_DLL). Hosts that want a single project in their solution mount with U1C_MONOLITH=ON (kernel + vendored deps compiled straight into the dll; U1C_DLL_DEPLOY_DIR adds a post-build copy) — see BUILD.md.

Directory

See the directory tree at the end of BUILD.md.

License

Apache License 2.0 — see LICENSE, NOTICE and THIRD_PARTY_NOTICES.md. This is an original, clean-room implementation; CONTRIBUTING.md states the provenance rules and tools/check_provenance.py is the mechanical gate.

3MF source probing

u1c::conv::probe_3mf(path) and ThreemfEngine::probe_3mf(path) return Result<ThreemfProbe> without initialization or assets. form retains the project-settings-entry test (Project / GenericModel). application contains the trimmed root model Application metadata; slicer identifies the declared producer, and is_snapmaker() checks for SourceSlicer::SnapmakerOrca. The file probe indexes ZIP entry names and reads only the root relationships, root model, and project settings needed for legacy inference. Payload integrity checks apply to entries the probe reads.

Explicit Snapmaker_Orca- and Creality_Print markers take priority over the shared OrcaSlicer metadata. Otherwise that metadata or an OrcaSlicer- Application identifies upstream Orca. Legacy Snapmaker projects use a BambuStudio- Application: these are inferred only when printer_model starts with Snapmaker , mixed_filament_definitions is a string, and filament_colour_mode is an array. Inference sets slicer_inferred = true. A Snapmaker printer name alone is insufficient. Unknown producers remain Unknown; malformed root XML, missing root models, or unreadable legacy settings return errors. Root model relationships are honored.

The local sample set contains 7 Snapmaker projects (1 explicit, 6 legacy), 13 Bambu projects, 10 Creality projects, and 1 upstream Orca project targeting Snapmaker U1. These signatures distinguish that sample set; metadata is not proof of authorship, and other versions or edited profiles may be ambiguous. Kernel-generated files can also carry a Snapmaker Application marker.

This changes the C++ return type and DLL ABI: rebuild the DLL and C++ hosts together, and replace old result.value() source-form reads with result.value().form. The C ABI u1c_probe_3mf retains its 0/1 source-form result.

Project migration uses the same in-memory source classifier as probe_3mf. Mixed slots still take precedence over definition rows. For rows, a classified Creality source selects Creality numbering; other known producers use Snapmaker numbering. Creality-specific tokens only infer numbering for unknown producers, with a warning. Conflicting tokens in known non-Creality files also produce a warning and cannot override the classified source's numbering.

Kernel errors

Fallible kernel operations return u1c::Result<T> (or Result<void>). Error is a value type with code(), kind(), and message() accessors. ErrorCode is a strongly typed enum describing the specific failure; error_kind(code) centrally maps it to one of the existing eight ErrKind categories. Callers cannot independently assign a category.

return u1c::fail(u1c::ErrorCode::InvalidGeometry, "triangle index out of range");

Use make_error(code, message) to construct an error value and fail(result.error()) to propagate it unchanged. Do not throw Error. guarded() at public entry points translates unexpected standard exceptions to UnexpectedException and other exceptions to UnknownException. Creating a failure can itself allocate; allocation failure is not guaranteed to be representable as a Result.

Diagnostic messages retain paths and technical details. Hosts should map ErrorCode to localized text and use ErrKind for category-level fallback; message wording is not an identifier. No JSON error payload is used, and enum numeric values are not a serialized protocol. The native DLL and consumers must be rebuilt together because the C++ Error layout and accessors changed. The legacy C interface continues to expose diagnostic text only.

Input geometry, transforms, scene structure and unsupported input features are classified as Parse; invalid caller options remain InvalidArgument. Missing input files use InputFileNotFound (NotFound), while missing or invalid deployment assets use Init codes. Unknown user-selected presets and presets incompatible with the selected machine have distinct codes.

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages