Sign in

    moonslicer

    Pure MoonBit 3D printing slicer: STL slicing, polygon offsetting, infill generation & G-code synthesis

    3d-printing
    slicer
    stl
    gcode
    geometry
    wasm
    Download zip
    Author
    Version
    0.1.2
    License
    Apache-2.0
    Last updated
    4 hours ago
    Downloads
    6

    #MoonSlicer


    #1. 项目概述

    MoonSlicer 是一个使用纯 MoonBit 语言开发的现代增材制造 3D 打印切片与刀路生成引擎。它能够将三维三角形网格模型(二进制与 ASCII 格式 STL)直接转换生成适用于 3D 打印机固件(Marlin / RepRap / Klipper)的标准 G-code 打印控制指令。

    本项目采用**零外部 FFI 依赖(Zero FFI)**的纯原生架构,所有计算几何求交、拓扑闭环、多孔偏置碰撞消解、多元填充几何生成、接缝起针优化、悬垂搭桥识别与物理送丝微积分算法均在 MoonBit 原生内存中自主实现。项目支持同时编译为原生机器码(Native)与 WebAssembly(WASM / Wasm-GC),具备极高的跨平台执行效率与确定性输出保证。


    #2. 核心架构与技术特性

    #2.1 三维网格解析与空间归一化

    • 流式 STL 解码:内建 IEEE 754 单精度浮点数解码器,原生支持标准 Binary STL 与文本 ASCII STL 的流式解析。
    • 自动对齐与热床居中:自动计算三维网格轴向包围盒(AABB),将模型底部平贴于 打印平面,并将几何质心自动平移对齐至热床中心 。

    #2.2 水平截面切片与拓扑闭环缝合

    • 解析平面求交:在任意层高 上对三维空间三角形进行线性解析求交,内建自适应 -微扰机制,杜绝截面恰好切过几何顶点的退化奇异。
    • 拓扑线段链式缝合 (-Chaining):针对切片产生的无序二维线段集合,基于空间首尾距离贪心匹配,将其精确重构成连续闭合的二维多边形轮廓环(Polygon2)。

    #2.3 ExPolygon 拓扑层级包含树

    • Jordan 奇偶深度判定:基于射线求交与多边形嵌套关系计算包含深度,偶数深度判定为独立实体外岛(CCW 逆时针,正面积),奇数深度判定为内部空腔内孔(CW 顺时针,负面积)。
    • 拓扑树表达:原生支持单层多独立实体(Multi-Island)与多层嵌套复杂通孔结构的树状表达,与现代主流切片器几何拓扑内核对齐。

    #2.4 间隙感知与偏置碰撞消解引擎

    • 角平分线法向量偏置:实现实体外壁向内收缩与内孔壁向外膨胀的角平分线偏移,内建斜接截断(Miter Limit)与边反转坍塌检查。
    • 欧氏间隙场分析 (Clearance Field Analysis):在生成多圈外壁前,精确评估孔与孔、孔与外轮廓之间的最小几何间隙,推导最大安全膨胀阈值 。
    • 自适应截断与重叠抑制 (Clamping & Wall Suppression):当特征狭窄时自动截断偏置步长;对于间隙不足以容纳多圈壁厚的狭窄区域,主动抑制生成重叠内壁(WallSuppressed),彻底杜绝重复挤出造成的喷嘴刮擦与过量溢料。
    • 后置几何交叉校验:轮廓生成后执行穷举线段交叉校验(edges_intersect),数学上杜绝自交或相交刀路输出。
    • Ramer-Douglas-Peucker 轮廓化简:提供 Polygon2::simplify 算法,在亚微米尺度下自适应剔除共线噪点与冗余顶点,杜绝高分辨率模型造成的打印机通讯抖动。

    #2.5 跨层表面分类与搭桥冷却控制

    • 三维几何覆盖比对:通过对比当前层与上下相邻层( 与 )的实体投影覆盖关系,精确判定 TopSolid(顶面/阶梯屋顶)、BottomSolid(底面/悬垂桥接)与 InternalSparse(内部区域)。
    • 悬垂搭桥风扇控制:当识别到悬垂搭桥表面时,自动触发高速冷却风扇指令(M106 S255)并按比例下调挤出流速(Flow Ratio)与移动速度,搭桥结束后自动恢复常规风速。

    #2.6 多元内部填充几何生成器

    引擎支持 4 种经典的增材制造内部轻量化填充模式:
    • Rectilinear (交替线性网格):45° 与 135° 奇偶层交替方向,平衡打印速度与层间附着力;
    • Grid (双向正交网格):每层同时打印双向正交交叉扫描线,提供刚性支撑骨架;
    • Triangles (等边三角晶格):0°、60°、120° 三向交叉成型,具备优异的面内全向抗剪切刚度;
    • Concentric (同心偏置环):自外轮廓向内核心逐层偏移同心环,极大减少空载空移,适合圆柱与弹性体材料;
    • 内孔全自动避空 (Hole Parity Clipping):所有填充模式均内嵌奇偶相交校验,遇到内部空腔自动断针避空。

    #2.7 起针接缝优化策略 (Seam Placement Modes)

    • SharpestCorner (最锐角隐藏):计算多边形顶点外角凸度,自动将起笔接缝对齐隐藏于构件最锐利的自然棱角处;
    • Nearest (最短空程):基于当前喷头坐标贪心选择最近顶点起跳,显著减少空走距离与拉丝;
    • Aligned (几何对齐):将全模型各层外壁起针点向指定空间方位(如热床后方中央)对齐排布;
    • Random (随机打散):随机散布各层起针顶点,消除圆柱外壁由于接缝聚集产生的纵向微小凸棱。

    #2.8 真实物理耗材质量与成本估算

    • 扁平跑道截面微积分 (Stadium Cross-section):严格依据 FDM 熔融挤出物理模型 计算微元体积 ,精准推导绝对坐标 E 轴送丝进给量。
    • 物理材料质量建模:内建常用 3D 打印耗材密度库(PLA: 、PETG: 、ABS: 、TPU: ),实时推算总耗材克重与成型原料成本。

    #2.9 交互式刀路可视化工具

    • 开箱即用:提供纯 HTML5 Canvas 架构的轻量级前端刀路查看器(examples/visualizer.html),无需本地服务器,双击即可在任意现代浏览器运行。
    • 分层与多色审视:支持拖拽滑块逐层查看、动画播放、以及外壁(红)、孔壁(橙)、内壁(绿)、顶底实心填充(青)、内部稀疏填充(黄)与碰撞消解事件 HUD 实时显示。


    #3. 切片处理管线

    +---------------------------------------------------------------+ | 输入:3D 模型文件 (Binary / ASCII STL) | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 1. STL 解码与热床居中对齐 (center_to_bed) | | 流式解析三角面,计算 AABB 包围盒并平移至热床中心 (0,0,0) | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 2. 截面解析求交 (slice_mesh_at_z) | | 各三角面与平面 Z = z_i 线性求交,引入 epsilon 微扰消奇异 | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 3. 拓扑线段闭环缝合 (stitch_segments_into_loops) | | 基于首尾 epsilon 距离贪心重组封闭多边形环 Polygon2 | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 4. ExPolygon 拓扑层级树构建 (build_expolygons) | | Jordan 奇偶深度判定:外岛 CCW (正面积) vs 内孔 CW (负面积) | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 5. 间隙感知偏置与碰撞消解 (generate_expolygon_perimeters) | | 距离场分析、自适应截断、薄壁抑制与后置相交校验 | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 6. 跨层表面分类与多元填充 (infill.mbt / surface.mbt) | | 顶底实心识别、4 种填充几何 (Rectilinear/Grid/Triangles/ | | Concentric) 与搭桥风扇增强 | +---------------------------------------------------------------+ | v +---------------------------------------------------------------+ | 7. 跑道截面挤出量微积分与 G-code 合成 (generate_gcode) | | 体积积分计算 E 轴进给量,注入温控、回抽、接缝与分层 G-code | +---------------------------------------------------------------+


    #4. 项目结构

    moonslicer/ ├── types.mbt # 切片配置参数、表面枚举、填充几何模式、材料密度库与接缝策略 ├── geom.mbt # 2D/3D 几何向量、线段求交、Polygon2、RDP 化简、ExPolygon 拓扑树 ├── stl.mbt # IEEE 754 float32 解码、Binary/ASCII STL 流式解析器 ├── slice.mbt # 三角形截面求交与拓扑线段链式闭环重构 ├── offset.mbt # 角平分线偏置算法、多孔间隙分析与碰撞消解引擎 ├── surface.mbt # 跨层表面分类引擎 (TopSolid / BottomSolid / InternalSparse) ├── infill.mbt # 多元填充生成器 (Rectilinear / Grid / Triangles / Concentric) ├── gcode.mbt # 跑道截面微积分、起针接缝排布、搭桥风控与 G-code 合成器 ├── pipeline.mbt # 端到端切片流程编排器与模型统计评估 ├── cmd/main/ # 独立命令行工具 CLI (slice / info / help) ├── fixtures/ # 标准测试模型库 (校准立方体、薄壁双孔干涉构件等) ├── examples/ # HTML5 Canvas 交互式刀路可视化工具 ├── *wbtest.mbt # 47 项白盒与极限边界测试套件 (覆盖碰撞消解、多元填充、RDP化简等) └── docs/ # 技术设计与量化基准白皮书 ├── architecture.md # 详细算法推导与工程设计文档 └── BENCHMARKS.md # 真实量化基准数据与极限边界测试报告


    #5. 快速上手

    #环境要求

    #编译与测试

    # 执行静态类型推导与语法检查 moon check # 验证 WebAssembly 目标架构兼容性 moon check --target wasm moon check --target wasm-gc # 运行全套 47 项白盒、集成与性能基准测试 moon test # 代码格式化规范检查 moon fmt --check


    #6. 命令行工具 (CLI)

    MoonSlicer 提供了开箱即用的命令行工具,支持三维模型元数据审视与切片代码生成。

    #6.1 模型信息审视 (info)

    读取 STL 文件并输出面片数量、三维尺寸与预估层数:

    moon run cmd/main -- info -i fixtures/dual_holes_collision.stl

    输出示例:
    Reading STL file: fixtures/dual_holes_collision.stl (5597 bytes)... ---------------------------------------- Mesh Inspection Report: Triangle Facets: 44 Bounding Width (X):30 mm Bounding Depth (Y):15 mm Bounding Height (Z):4 mm Z Range: [0, 4] mm Estimated Layers: 19 (at 0.2mm) ----------------------------------------

    #6.2 执行高级切片生成 G-code (slice)

    针对指定模型执行全流程切片,支持自定义填充模式、接缝排布、打印材料与成本参数:

    moon run cmd/main -- slice -i fixtures/dual_holes_collision.stl -o output.gcode \ --layer-height 0.2 \ --initial-height 0.28 \ --line-width 0.4 \ --walls 2 \ --bottom-solid 3 \ --top-solid 3 \ --density 0.2 \ --pattern grid \ --seam sharpest \ --material pla \ --cost-per-kg 120.0 \ --speed 50.0

    输出示例:
    Loading model from: fixtures/dual_holes_collision.stl... Parsing mesh (5597 bytes)... Mesh: 44 facets, 30x15x4 mm Slicing layers (height: 0.2 mm, pattern: Grid, seam: SharpestCorner)... Synthesizing G-code (19 layers)... ---------------------------------------- Slicing Completed Successfully! Output File: output.gcode Total Layers: 19 Collisions Resolved:38 Filament Extruded: 317.24 mm Filament Mass: 0.95 g Estimated Cost: ¥0.11 Est. Print Time: 5.87 min ----------------------------------------


    #7. 交互式可视化工具 (Visualizer)

    项目在 examples/visualizer.html 中内置了基于 HTML5 Canvas 的跨平台刀路可视化工具:

    • 零依赖即开即用:直接双击在任意主流浏览器(Chrome、Edge、Safari、Firefox)中打开,无需配置本地 Web 服务。
    • 逐层审视与动画播放:支持拖拽滑块切换观察任意单层刀路,或以设定速率自动播放打印行进动画。
    • 多色分层呈现:
      • 红色:外壁轮廓(Outer Perimeter)
      • 橙色:内孔轮廓(Hole Perimeter)
      • 绿色:内部外壁(Inner Perimeter)
      • 青色:顶底层密实填充(Solid Infill)
      • 黄色:内部轻量化稀疏填充(Sparse Infill)
      • 灰色虚线:空载快速移动(G0 Travel)
    • 实时状态 HUD:实时显示当前层高、耗材累计消耗、预估耗时以及碰撞消解事件统计。


    #8. 真实基准数据与测试覆盖 (Benchmarks & Testing)

    项目提供完整的量化性能基准与极限边界自动化测试,详细评测报告参见 BENCHMARKS.md。

    评测模块基准指标 / 极限场景实测表现
    偏置碰撞消解 密集 6 孔阵列(间隙 1.2mm)100% 杜绝孔间干涉,交叉相交数为 0
    轮廓 RDP 化简40 个共线冗余顶点闭合多边形顶点压缩率 90.0%,截面积偏差严格为 0.000%
    多元填充生成Rectilinear, Grid, Triangles, Concentric4 种工业填充拓扑自动避空,线性缩放
    物理微积分PLA/PETG/ABS/TPU 耗材质量与成本推算扁平跑道截面连续积分,误差 < 0.05%
    极限边界防线退化三角面、0.25mm 薄壁、0% 与 100% 填充、负坐标居中47 项自动化白盒与黑盒测试 100% 通过


    #9. 技术规格与路线图 (Specifications & Roadmap)

    #当前支持的技术规格

    维度当前功能支持
    输入模型格式严格 2-流形闭合三角形网格(Binary IEEE 754 与 ASCII 格式 STL)
    拓扑几何支持任意平面封闭多边形、单层多独立岛屿、多层嵌套内孔、RDP 几何轮廓自适应化简
    轮廓偏置机制双向角平分线法向量偏置,支持间隙场分析、自适应截断与薄壁多层壁抑制
    接缝起针策略最锐角隐藏(SharpestCorner)、最短空程(Nearest)、几何对齐(Aligned)、随机(Random)
    内部填充样式Rectilinear (线性交替)、Grid (双向正交)、Triangles (三角晶格)、Concentric (同心环)
    挤出微积分模型扁平跑道截面(Stadium Cross-section)物理微积分,绝对坐标 E 轴推进
    材料质量建模内建 PLA、PETG、ABS、TPU 材料密度与成型成本实时推算
    搭桥风扇控制悬垂搭桥表面自动触发满速冷却风扇(M106 S255)与自适应流量修正
    固件格式输出标准 Marlin / RepRap / Klipper 兼容 G-code

    #后续演进路线图 (Roadmap)


    #10. 开源协议

    本项目采用 Apache-2.0 开源协议。

    BBox3

    pub(all) struct BBox3 {
    min : Vec3
    max : Vec3
    } derive(Eq,
    Debug
    )

    3D Axis-Aligned Bounding Box.

    BBox3::center

    fn BBox3::center(self : BBox3) -> Vec3

    BBox3::depth

    fn BBox3::depth(self : BBox3) -> Double

    BBox3::height

    fn BBox3::height(self : BBox3) -> Double

    BBox3::new

    fn BBox3::new(min : Vec3, max : Vec3) -> BBox3

    BBox3::width

    fn BBox3::width(self : BBox3) -> Double

    ExPolygon

    pub(all) struct ExPolygon {
    contour : Polygon2
    holes : Array[Polygon2]
    } derive(Eq,
    Debug
    )

    An exterior polygon contour together with its interior holes (PrusaSlicer-compatible ExPolygon).

    ExPolygon::area

    fn ExPolygon::area(self : ExPolygon) -> Double

    Net cross-sectional area (outer contour area minus all interior holes).

    ExPolygon::contains_point

    fn ExPolygon::contains_point(self : ExPolygon, pt : Vec2) -> Bool

    Point containment: inside the outer contour and not inside any interior hole.

    ExPolygon::interior_point

    fn ExPolygon::interior_point(self : ExPolygon) -> Vec2

    Find a guaranteed interior point in the solid material (not inside any hole).

    ExPolygon::new

    fn ExPolygon::new(contour : Polygon2, holes? : Array[Polygon2]) -> ExPolygon

    ExPolygonPerimeters

    pub(all) struct ExPolygonPerimeters {
    outer_walls : Array[Polygon2]
    hole_walls : Array[Array[Polygon2]]
    infill_boundary : ExPolygon?
    collisions : Array[OffsetCollisionEvent]
    } derive(
    Debug
    )

    Structure holding perimeter paths, infill boundary, and collision resolution events.

    FilamentMaterial

    pub(all) enum FilamentMaterial {
    PLA
    PETG
    ABS
    TPU
    } derive(Eq,
    Debug
    )

    Standard 3D printing filament materials with physical density (g/cm^3).

    FilamentMaterial::density

    fn FilamentMaterial::density(self : FilamentMaterial) -> Double

    GCodeResult

    pub(all) struct GCodeResult {
    gcode : String
    total_filament_mm : Double
    total_filament_grams : Double
    estimated_cost : Double
    total_layers : Int
    estimated_print_time_sec : Double
    travel_time_sec : Double
    extrusion_time_sec : Double
    total_collisions_resolved : Int
    } derive(
    Debug
    )

    Formatted G-code result containing the output string and comprehensive physical slicing statistics.

    InfillPattern

    pub(all) enum InfillPattern {
    Rectilinear
    Grid
    Triangles
    Concentric
    } derive(Eq,
    Debug
    )

    Supported internal infill geometric patterns.

    Mesh3

    pub(all) struct Mesh3 {
    triangles : Array[Triangle3]
    bounds : BBox3
    } derive(Eq,
    Debug
    )

    Mesh3::center_to_bed

    fn Mesh3::center_to_bed(self : Mesh3) -> Mesh3

    Center the mesh on the print bed: X/Y centered around (0,0), Z grounded at 0.0.

    Mesh3::from_triangles

    fn Mesh3::from_triangles(triangles : Array[Triangle3]) -> Mesh3

    Construct a Mesh3 from an array of triangles and automatically compute its BBox3.

    MeshSliceStats

    pub(all) struct MeshSliceStats {
    triangle_count : Int
    width : Double
    depth : Double
    height : Double
    estimated_layers : Int
    min_z : Double
    max_z : Double
    } derive(
    Debug
    )

    Summary statistics for a 3D mesh slicing job.

    OffsetCollisionEvent

    pub(all) struct OffsetCollisionEvent {
    hole_a_idx : Int
    hole_b_idx : Int
    clearance : Double
    requested_offset : Double
    clamped_offset : Double
    action : String
    } derive(Eq,
    Debug
    )

    Record of an offset path collision and the resolution action taken.

    Polygon2

    pub(all) struct Polygon2 {
    points : Array[Vec2]
    } derive(Eq,
    Debug
    )

    A closed 2D polygon boundary.

    Polygon2::area

    fn Polygon2::area(self : Polygon2) -> Double

    Signed area via Green's theorem / Shoelace formula. Positive area = CCW (outer contour), Negative area = CW (hole).

    Polygon2::centroid

    fn Polygon2::centroid(self : Polygon2) -> Vec2

    Polygon2::contains_point

    fn Polygon2::contains_point(self : Polygon2, pt : Vec2) -> Bool

    Ray-casting point-in-polygon containment test (Even-Odd rule).

    Polygon2::contains_polygon

    fn Polygon2::contains_polygon(self : Polygon2, other : Polygon2) -> Bool

    Check whether this polygon completely contains another polygon. A smaller polygon can never contain a larger one, and all vertices of the other must lie inside.

    Polygon2::distance_to_polygon

    fn Polygon2::distance_to_polygon(self : Polygon2, other : Polygon2) -> Double

    Minimum clearance distance between two closed 2D polygons.

    Polygon2::edges_intersect

    fn Polygon2::edges_intersect(self : Polygon2, other : Polygon2) -> Bool

    Check whether any edge of this polygon intersects any edge of another polygon.

    Polygon2::ensure_ccw

    fn Polygon2::ensure_ccw(self : Polygon2) -> Polygon2

    Polygon2::ensure_cw

    fn Polygon2::ensure_cw(self : Polygon2) -> Polygon2

    Polygon2::intersects_polygon

    fn Polygon2::intersects_polygon(self : Polygon2, other : Polygon2) -> Bool

    Check whether two closed 2D polygons intersect or overlap (edges cross or containment).

    Polygon2::is_ccw

    fn Polygon2::is_ccw(self : Polygon2) -> Bool

    Polygon2::nearest_vertex_idx

    fn Polygon2::nearest_vertex_idx(self : Polygon2, target : Vec2) -> Int

    Find the index of the vertex closest to target in Euclidean distance.

    Polygon2::new

    fn Polygon2::new(points : Array[Vec2]) -> Polygon2

    Polygon2::reverse

    fn Polygon2::reverse(self : Polygon2) -> Polygon2

    Polygon2::rotate_start

    fn Polygon2::rotate_start(self : Polygon2, start_idx : Int) -> Polygon2

    Rotate polygon vertex array cyclically so points[0] becomes the vertex at start_idx.

    Polygon2::sharpest_corner_idx

    fn Polygon2::sharpest_corner_idx(self : Polygon2) -> Int

    Find the index of the vertex with the sharpest convex corner (minimum interior angle). Used by SeamMode::SharpestCorner to hide seam zits at natural edges.

    Polygon2::simplify

    fn Polygon2::simplify(self : Polygon2, epsilon : Double) -> Polygon2

    Ramer-Douglas-Peucker (RDP) polygon simplification algorithm. Reduces collinear and jitter vertices within perpendicular distance epsilon.

    SeamMode

    pub(all) enum SeamMode {
    Nearest
    Aligned
    SharpestCorner
    Random
    } derive(Eq,
    Debug
    )

    Seam placement strategies for perimeter start vertices.
    impl Show for SeamMode

    Segment2

    pub(all) struct Segment2 {
    p1 : Vec2
    p2 : Vec2
    } derive(Eq,
    Debug
    )

    Segment2::direction

    fn Segment2::direction(self : Segment2) -> Vec2

    Segment2::distance_to_point

    fn Segment2::distance_to_point(self : Segment2, pt : Vec2) -> Double

    Distance from a 2D point to this line segment.

    Segment2::distance_to_segment

    fn Segment2::distance_to_segment(self : Segment2, other : Segment2) -> Double

    Minimum Euclidean distance between two line segments.

    Segment2::intersect

    fn Segment2::intersect(self : Segment2, other : Segment2) -> Vec2?

    Test intersection between two 2D line segments. Returns Some(intersection_pt) or None.

    Segment2::length

    fn Segment2::length(self : Segment2) -> Double

    Segment2::new

    fn Segment2::new(p1 : Vec2, p2 : Vec2) -> Segment2

    SliceLayer

    pub(all) struct SliceLayer {
    z : Double
    polygons : Array[Polygon2]
    expolygons : Array[ExPolygon]
    } derive(
    Debug
    )

    A sliced 2D layer containing reconstructed boundary polygons and topological ExPolygons.

    SliceLayer::new

    fn SliceLayer::new(z : Double, polygons : Array[Polygon2], expolygons? : Array[ExPolygon]) -> SliceLayer

    SlicerConfig

    pub(all) struct SlicerConfig {
    layer_height : Double
    initial_layer_height : Double
    line_width : Double
    wall_count : Int
    bottom_solid_layers : Int
    top_solid_layers : Int
    infill_density : Double
    infill_angle : Double
    infill_pattern : InfillPattern
    seam_mode : SeamMode
    material : FilamentMaterial
    filament_cost_per_kg : Double
    filament_diameter : Double
    nozzle_temp : Int
    bed_temp : Int
    fan_speed : Int
    bridge_fan_speed : Int
    bridge_speed : Double
    bridge_flow_ratio : Double
    print_speed : Double
    solid_infill_speed : Double
    travel_speed : Double
    retract_distance : Double
    retract_speed : Double
    } derive(
    Debug
    )

    Slicing and printing configuration.

    SlicerConfig::default

    fn SlicerConfig::default() -> SlicerConfig

    Default printing profile (0.4mm nozzle, 0.2mm layer height, 2 walls, 3 top/bottom solid layers, 20% infill).

    SlicerError

    pub(all) enum SlicerError {
    InvalidStl(String)
    IoError(String)
    EmptyMesh
    SlicingFailed(String)
    } derive(Eq,
    Debug
    )

    impl Show for SlicerError

    SurfaceType

    pub(all) enum SurfaceType {
    TopSolid
    BottomSolid
    InternalSparse
    } derive(Eq,
    Debug
    )

    PrusaSlicer-compatible surface region classification.
    impl Show for SurfaceType

    Triangle3

    pub(all) struct Triangle3 {
    normal : Vec3
    v1 : Vec3
    v2 : Vec3
    v3 : Vec3
    } derive(Eq,
    Debug
    )

    Triangle3::max_z

    fn Triangle3::max_z(self : Triangle3) -> Double

    Triangle3::min_z

    fn Triangle3::min_z(self : Triangle3) -> Double

    Triangle3::new

    fn Triangle3::new(normal : Vec3, v1 : Vec3, v2 : Vec3, v3 : Vec3) -> Triangle3

    Vec2

    pub(all) struct Vec2 {
    x : Double
    y : Double
    } derive(Eq,
    Debug
    )

    Vec2::add

    fn Vec2::add(self : Vec2, other : Vec2) -> Vec2

    Vec2::cross

    fn Vec2::cross(self : Vec2, other : Vec2) -> Double

    2D cross product (perp-dot product): u.x * v.y - u.y * v.x

    Vec2::distance

    fn Vec2::distance(self : Vec2, other : Vec2) -> Double

    Vec2::distance_sq

    fn Vec2::distance_sq(self : Vec2, other : Vec2) -> Double

    Vec2::dot

    fn Vec2::dot(self : Vec2, other : Vec2) -> Double

    Vec2::left_normal

    fn Vec2::left_normal(self : Vec2) -> Vec2

    Left-hand 90-degree normal: (-y, x)

    Vec2::length

    fn Vec2::length(self : Vec2) -> Double

    Vec2::length_sq

    fn Vec2::length_sq(self : Vec2) -> Double

    Vec2::new

    fn Vec2::new(x : Double, y : Double) -> Vec2

    Vec2::normalize

    fn Vec2::normalize(self : Vec2) -> Vec2

    Vec2::scale

    fn Vec2::scale(self : Vec2, factor : Double) -> Vec2

    Vec2::sub

    fn Vec2::sub(self : Vec2, other : Vec2) -> Vec2

    Vec2::zero

    fn Vec2::zero() -> Vec2

    Vec3

    pub(all) struct Vec3 {
    x : Double
    y : Double
    z : Double
    } derive(Eq,
    Debug
    )

    Vec3::add

    fn Vec3::add(self : Vec3, other : Vec3) -> Vec3

    Vec3::cross

    fn Vec3::cross(self : Vec3, other : Vec3) -> Vec3

    Vec3::distance

    fn Vec3::distance(self : Vec3, other : Vec3) -> Double

    Vec3::dot

    fn Vec3::dot(self : Vec3, other : Vec3) -> Double

    Vec3::length

    fn Vec3::length(self : Vec3) -> Double

    Vec3::length_sq

    fn Vec3::length_sq(self : Vec3) -> Double

    Vec3::new

    fn Vec3::new(x : Double, y : Double, z : Double) -> Vec3

    Vec3::normalize

    fn Vec3::normalize(self : Vec3) -> Vec3

    Vec3::scale

    fn Vec3::scale(self : Vec3, factor : Double) -> Vec3

    Vec3::sub

    fn Vec3::sub(self : Vec3, other : Vec3) -> Vec3

    Vec3::zero

    fn Vec3::zero() -> Vec3

    build_expolygons

    fn build_expolygons(polygons : Array[Polygon2]) -> Array[ExPolygon]

    Build topological hierarchy (ExPolygons) from an arbitrary array of sliced closed polygons. Accurately classifies multi-island outer contours vs inner holes and nested islands.

    calculate_delta_e

    fn calculate_delta_e(move_length : Double, line_width : Double, layer_height : Double, filament_diameter : Double) -> Double

    Calculate extrusion length (delta E) for moving distance L with given filament diameter.

    calculate_extrusion_area

    fn calculate_extrusion_area(line_width : Double, layer_height : Double) -> Double

    Calculate extrusion cross-sectional area based on nozzle line width and layer height. Uses stadium cross-section (flat rectangle core with two semi-circular rounded caps).

    classify_infill_segment

    fn classify_infill_segment(seg : Segment2, layer_idx : Int, layers : Array[SliceLayer], config : SlicerConfig) -> SurfaceType

    Classify a single infill segment by testing if its midpoint has support below and ceiling above.

    classify_island_surface

    fn classify_island_surface(island : ExPolygon, layer_idx : Int, layers : Array[SliceLayer], config : SlicerConfig) -> SurfaceType

    Classify an individual 2D island (ExPolygon) by comparing with adjacent layers.

    classify_layer

    fn classify_layer(layer_idx : Int, total_layers : Int, config : SlicerConfig) -> SurfaceType

    Classify the overall layer surface type based on layer index and solid layer settings.

    format_f3

    fn format_f3(val : Double) -> String

    Helper to format a Double to 3 decimal places without exponential notation.

    generate_expolygon_concentric_infill

    fn generate_expolygon_concentric_infill(expoly : ExPolygon, density : Double, line_width : Double) -> Array[Segment2]

    Generate Concentric infill: nested inward offsets from perimeter towards polygon center.

    generate_expolygon_grid_infill

    fn generate_expolygon_grid_infill(expoly : ExPolygon, density : Double, line_width : Double, base_angle : Double) -> Array[Segment2]

    Generate Grid infill: prints dual orthogonal scanlines on every layer.

    generate_expolygon_infill

    fn generate_expolygon_infill(expoly : ExPolygon, pattern : InfillPattern, density : Double, line_width : Double, layer_idx : Int, base_angle : Double) -> Array[Segment2]

    Universal infill dispatcher generating toolpath segments based on the selected InfillPattern.

    generate_expolygon_perimeters

    fn generate_expolygon_perimeters(expoly : ExPolygon, wall_count : Int, line_width : Double) -> ExPolygonPerimeters

    Generate perimeters for an ExPolygon with full collision detection and resolution. Prevents contour overlap between adjacent holes or between holes and outer walls.

    generate_expolygon_rectilinear_infill

    fn generate_expolygon_rectilinear_infill(expoly : ExPolygon, density : Double, line_width : Double, angle_deg : Double) -> Array[Segment2]

    Generate rectilinear infill lines for an ExPolygon (contour with holes). Automatically clips infill lines across all interior holes.

    generate_expolygon_triangles_infill

    fn generate_expolygon_triangles_infill(expoly : ExPolygon, density : Double, line_width : Double, base_angle : Double) -> Array[Segment2]

    Generate Triangles infill: prints 3 sets of scanlines at 0, 60, and 120 degrees to form triangular lattices.

    generate_gcode

    fn generate_gcode(layers : Array[SliceLayer], config : SlicerConfig, bed_center_x? : Double, bed_center_y? : Double) -> GCodeResult

    Synthesize standard Marlin/RepRap G-code from sliced layers with PrusaSlicer feature alignment.

    generate_perimeters

    fn generate_perimeters(poly : Polygon2, wall_count : Int, line_width : Double) -> (Array[Polygon2], Polygon2?)

    Generate multiple perimeter walls for a single polygon contour. Returns (perimeters, infill_boundary).

    generate_rectilinear_infill

    fn generate_rectilinear_infill(poly : Polygon2, density : Double, line_width : Double, angle_deg : Double) -> Array[Segment2]

    Generate rectilinear infill lines for a boundary polygon.
    • density: 0.0 to 1.0 (e.g. 0.2 = 20%)
    • line_width: extrusion width in mm (e.g. 0.4)
    • angle_deg: angle of infill lines in degrees (e.g. 45.0 or 135.0)

    get_mesh_slice_stats

    fn get_mesh_slice_stats(mesh : Mesh3, config? : SlicerConfig) -> MeshSliceStats

    Calculate summary statistics for slicing a mesh.

    intersect_triangle_plane

    fn intersect_triangle_plane(tri : Triangle3, z : Double) -> Segment2?

    Intersect a 3D triangle with horizontal plane Z = z. Returns Some(Segment2) if intersection is a valid segment, None otherwise.

    math_cos

    fn math_cos(rad : Double) -> Double

    High-precision cosine approximation.

    math_sin

    fn math_sin(rad : Double) -> Double

    High-precision sine approximation for arbitrary angles.

    offset_polygon_inward

    fn offset_polygon_inward(poly : Polygon2, d : Double, miter_limit? : Double) -> Polygon2?

    Offset a single closed polygon inward by distance d (d > 0). Uses angle bisector normal displacement with miter clamping. Returns Some(offset_poly) if valid, or None if the polygon collapsed.

    offset_polygon_outward

    fn offset_polygon_outward(poly : Polygon2, d : Double, miter_limit? : Double) -> Polygon2?

    Offset a hole polygon outward into the surrounding solid material. Uses angle bisector normal displacement on clockwise hole boundary.

    parse_stl

    fn parse_stl(data : Bytes) -> Result[Mesh3, SlicerError]

    Parse an STL file (binary or ASCII).

    read_f32_le

    fn read_f32_le(data : Bytes, offset : Int) -> Double

    Decode little-endian IEEE 754 32-bit float from bytes.

    read_u32_le

    fn read_u32_le(data : Bytes, offset : Int) -> Int

    Decode little-endian uint32.

    slice_mesh

    fn slice_mesh(mesh : Mesh3, config : SlicerConfig) -> Array[SliceLayer]

    Slice an entire 3D mesh into layers according to layer_height settings.

    slice_mesh_at_z

    fn slice_mesh_at_z(mesh : Mesh3, z : Double) -> SliceLayer

    Slice a 3D mesh at a specific Z height into closed polygons.

    slice_mesh_to_gcode

    fn slice_mesh_to_gcode(mesh : Mesh3, config? : SlicerConfig, bed_center_x? : Double, bed_center_y? : Double) -> GCodeResult

    Slice a 3D mesh into G-code end-to-end.

    slice_stl_bytes_to_gcode

    fn slice_stl_bytes_to_gcode(bytes : Bytes, config? : SlicerConfig, bed_center_x? : Double, bed_center_y? : Double) -> Result[GCodeResult, SlicerError]

    Parse raw STL bytes (ASCII or binary) and slice directly to G-code.

    stitch_segments_into_loops

    fn stitch_segments_into_loops(segments : Array[Segment2], tolerance? : Double) -> Array[Polygon2]

    Stitch a collection of unordered 2D line segments into closed Polygon2 loops.