ConstructCraft

cc_skp API

← API reference · Generated from the source by cargo run -p api_doc; edit the doc comments, not this page.

SketchUp (.skp) files: reader (current and legacy formats, scenes and per-definition instanced scenes) and writer (create, edit). Derived from the MIT-licensed OpenSKP toolkit (see LICENSE); no external dependencies. Lengths in the parsed model are inches, as in the file.

use cc_skp::{ParseOptions, SkpFile};
let model = SkpFile::open("building.skp")?.parse(&ParseOptions::default())?;
println!("{} {} definitions", model.version, model.definitions.len());

Modules

Module Items Summary
cc_skp 0 SketchUp (.skp) files: reader (current and legacy formats, scenes and per-definition instanced scenes) and writer (create, edit).
cc_skp::create 27 Create new legacy-format (v17) .skp files from scratch.
cc_skp::create::archive 16 ArchiveWriter - the write-side mirror of the legacy reader’s MFC CArchive slot/class-ref bookkeeping, plus every entity record encoder the builder uses.
cc_skp::create::geometry 13 Small geometry/linear-algebra helpers for the writer.
cc_skp::create::scaffold_blank_v17 23 The blank-document scaffold every new file is spliced into, and the fixed positions inside it the writer patches.
cc_skp::curves 7 Loose-edge chaining and analytic-arc recovery, shared by the baked and the instanced scene builders (Python port extension: openskp/_curves.py; the C++ port has no equivalent).
cc_skp::deflate 2 A small pure-Rust DEFLATE (RFC 1951) / zlib (RFC 1950) compressor: hash-chain LZ77 with optional one-step lazy matching, and per block the cheapest of stored / fixed-Huffman / dynamic-Huffman coding.
cc_skp::earcut 4 2D ear-clipping with holes (earcut.cpp): EarPoint and earcut_2d.
cc_skp::edit 9 Load an existing legacy-format .skp file and rebuild it as a new, independent SkpBuilder (edit.hpp / edit.cpp, itself a port of Python’s openskp.edit).
cc_skp::errors 3 Structured parse errors (errors.hpp / errors.cpp).
cc_skp::face_groups 11 Local-space face grouping shared by the baked (scene_build.rs) and instanced (instanced_scene_build.rs) scene builders (face_groups.hpp / face_groups.cpp).
cc_skp::inflate 7 Pure-Rust DEFLATE (RFC 1951) and zlib (RFC 1950) decoder, replacing the parts of miniz’s tinfl / mz_uncompress the reader uses.
cc_skp::instanced_scene 8 The instanced scene graph (instanced_scene.hpp).
cc_skp::instanced_scene_build 1 The instanced scene builder (instanced_scene.cpp’s build_instanced_scene_raw), plus the Python port’s loose-edge curve resources (instanced_scene.py’s curve_resources).
cc_skp::internal 19 Reader infrastructure shared by the VFF reader, the legacy reader and the scene builders (internal.hpp).
cc_skp::internal::build_model 1 Shapes a RawParsed into the public SkpModel (model.cpp’s build_model).
cc_skp::internal::bytes 10 Bounds-checked little-endian readers, var-ints and the TLV walkers (tlv.cpp).
cc_skp::internal::core 7 The VFF (2021+) reader: ZIP container, material/style XML, and the model.dat record walk (core.cpp).
cc_skp::internal::geometry 8 VFF geometry, layer, material-id and definition collection (geometry.cpp).
cc_skp::internal::pages_dimensions 6 VFF (2021+) scenes (“pages”) and linear dimensions (pages_dimensions.cpp, itself a port of Python’s _core.py).
cc_skp::internal::strconv 4 C library string-to-number conversions with the C++ std::stoi / std::stoll / std::stod semantics the reader relies on: leading whitespace is skipped, the longest valid prefix is converted, trailing text is ignored, and “no conversion” or “out of range” is None (where the C++ would throw).
cc_skp::internal::transforms 5 Instance transform helpers (transforms.cpp).
cc_skp::internal::vff 4 Header, version and meta.dat helpers (vff.cpp).
cc_skp::internal::xml 7 Hand-written equivalents of the std::regex patterns core.cpp uses to pull attributes out of material.xml / style.xml.
cc_skp::legacy 22 Legacy (pre-2021 MFC CArchive) reader: SketchUp 3 through 2020 (legacy.cpp).
cc_skp::legacy::archive 7 The MFC object-graph walk (legacy.cpp’s struct Archive, the per-class readers and walk_model).
cc_skp::legacy::pages 2 Scenes (CViewPage records) in a classic file’s document tail (legacy.cpp’s scan_pages_for_layers and read_page_list).
cc_skp::legacy::reader 3 The bounds-checked cursor the legacy archive reads through (legacy.cpp’s struct R).
cc_skp::model 38 The parsed SketchUp model (model.hpp / model.cpp).
cc_skp::observability 10 Parse progress and log callbacks (observability.hpp).
cc_skp::parser 4 Public entry points (parser.hpp / parser.cpp).
cc_skp::scene 9 The baked, world-space scene (scene.hpp).
cc_skp::scene_build 17 The baked scene builder (scene.cpp’s build_scene_raw), plus the Python port’s loose-edge curve sets (scene.py’s curve_sets).
cc_skp::triangulator 3 Face normals and planar-face triangulation (triangulator.hpp / triangulator.cpp).
cc_skp::zip 5 Minimal in-memory ZIP reader replacing the miniz mz_zip_reader_* calls core.cpp makes: init from memory, file count/stat, locate by name, and extract to memory (stored or deflated, CRC-checked).

cc_skp

crates/cc_skp/src/lib.rs

Re-exports

cc_skp::create

crates/cc_skp/src/create/mod.rs

Create new legacy-format (v17) .skp files from scratch. A from-scratch binary writer for the same MFC CArchive object-stream format the legacy reader decodes, built by inverting that reader’s own proven logic (the class-ref/back-ref protocol, entity preambles, drawbase records). Ported from OpenSKP’s C++ create.cpp (itself a port of the SketchUp-SDK-cross-checked Python writer) and kept byte-for-byte identical to it. No SketchUp SDK is involved at any point. Scope: planar faces from vertex coordinates (vertices/edges shared automatically wherever coordinates coincide exactly), faces with holes, auto_triangulate fan-splitting of non-planar polygons; solid-color and PNG/JPEG-textured materials with optional explicit UV positioning; named layers; reusable component definitions with positioned instances; groups; nested definitions and nested group instances; per-instance rotation and hidden state; custom attribute dictionaries; true CArcCurve circles/arcs and CCurve polylines; Image entities; free linear dimensions, leader texts, construction lines/points and section planes. Coordinates are in inches, SketchUp’s native internal unit. Every file opens to the standard “Iso” view (parallel projection, from the (1, -1, 1) octant). The blank scaffold, and why it’s there. Every legacy .skp carries a header/material- manager/style-and-font-manager region that is only understood well enough to preserve it byte-for-byte and renumber the few internal references that shift when geometry is inserted. So rather than synthesize it, new files are built by splicing genuinely-written records into a bundled minimal empty document (see scaffold_blank_v17). Those template bytes came from Trimble’s own SDK (SUModelCreate + a bare save) - SketchUp’s built-in empty-document boilerplate (default style, Layer0, system font references), the same bytes any new SketchUp document contains. Everything else - the entity encoding, the object-graph protocol, the flag bytes real SketchUp silently requires, the tail renumbering - is independently reverse-engineered.

use cc_skp::create::{create, FaceOptions};
let mut builder = create();
let red = builder.add_material("Red", [255, 0, 0], None)?;
let roof = builder.add_layer("Roof", &Default::default())?;
let options = FaceOptions { material: Some(red), layer: Some(roof), ..Default::default() };
builder.add_face(&[[0.0, 0.0, 0.0], [100.0, 0.0, 0.0], [100.0, 100.0, 0.0], [0.0, 100.0, 0.0]], &options)?;
builder.save("output.skp")?;

Re-exports

Items: Point3 · Matrix3x3 · Rotation · UvPoint · UvCorrespondence · DEFAULT_DIMENSION_OFFSET · DEFAULT_TEXT_LEADER · SkpWriteError · AttributeValue · AttributeDict · MaterialColor · DocumentOptions · GuideOptions · FaceOptions · CircleOptions · ArcOptions · PolylineOptions · DefinitionOptions · LayerOptions · InstanceOptions · GroupOptions · GroupInstanceOptions · ImageOptions · DefinitionHandle · SkpBuilder · create · ComponentDefinitionBuilder

type alias Point3

pub type Point3 = [f64; 3]

A 3D point (x, y, z) in inches.

type alias Matrix3x3

pub type Matrix3x3 = [f64; 9]

Row-major 3x3 rotation/scale matrix.

type alias Rotation

pub type Rotation = (Point3, f64)

A rotation as (axis, angle in radians), right-hand rule; the axis need not be unit length.

type alias UvPoint

pub type UvPoint = (Point3, [f64; 2])

One (world point, (u, v)) correspondence for explicit texture positioning.

type alias UvCorrespondence

pub type UvCorrespondence = Vec<UvPoint>

Exactly 3 UvPoints - the minimum that fully determines an affine UV mapping.

const DEFAULT_DIMENSION_OFFSET

pub const DEFAULT_DIMENSION_OFFSET: f64

The C++ default for SkpBuilder::add_dimension’s offset, in inches.

const DEFAULT_TEXT_LEADER

pub const DEFAULT_TEXT_LEADER: Point3

The C++ default for SkpBuilder::add_text’s leader, in inches.

struct SkpWriteError

pub struct SkpWriteError

Raised when a .skp file cannot be constructed.

Traits: Clone, Debug, PartialEq, Eq, fmt::Display, std::error::Error

Some fields are private.

Methods

enum AttributeValue

pub enum AttributeValue

A custom attribute value, one variant per SketchUp attribute type this format supports.

Traits: Clone, Debug, PartialEq, From<&str>, From<String>, From<i32>, From<f64>, From<bool>

Variants

type alias AttributeDict

pub type AttributeDict = BTreeMap<String, AttributeValue>

A named dictionary of custom key/value metadata - the same mechanism SketchUp’s own “dynamic component” attributes use. Keys are written in sorted order.

trait MaterialColor

pub trait MaterialColor

A material color: an opaque Color3 (alpha 255) or a full Color4.

Implemented by (2): cc_skp::model::Color3, cc_skp::model::Color4

Required and provided items

struct DocumentOptions

pub struct DocumentOptions

Display settings supported by the legacy document scaffold, for SkpBuilder::set_document_options.

Traits: Clone, Debug, PartialEq, Default

Fields

struct GuideOptions

pub struct GuideOptions

Options for add_construction_line / add_construction_point on SkpBuilder and ComponentDefinitionBuilder.

Traits: Clone, Debug, Default, PartialEq, Eq

Fields

struct FaceOptions

pub struct FaceOptions

Options for add_face.

Traits: Clone, Debug, PartialEq, Default

Fields

struct CircleOptions

pub struct CircleOptions

Options for add_circle.

Traits: Clone, Debug, PartialEq, Default

Fields

struct ArcOptions

pub struct ArcOptions

Options for add_arc.

Traits: Clone, Copy, Debug, PartialEq, Default

Fields

struct PolylineOptions

pub struct PolylineOptions

Options for add_polyline.

Traits: Clone, Copy, Debug, Default, PartialEq, Eq

Fields

struct DefinitionOptions

pub struct DefinitionOptions

Options for SkpBuilder::add_component_definition.

Traits: Clone, Debug, PartialEq, Default

Fields

struct LayerOptions

pub struct LayerOptions

Options for SkpBuilder::add_layer.

Traits: Clone, Debug, Default, PartialEq

Fields

struct InstanceOptions

pub struct InstanceOptions

Options for add_instance.

Traits: Clone, Debug, PartialEq, Default

Fields

struct GroupOptions

pub struct GroupOptions

Options for SkpBuilder::add_group.

Traits: Clone, Debug, PartialEq, Default

Fields

struct GroupInstanceOptions

pub struct GroupInstanceOptions

Options for ComponentDefinitionBuilder::add_group_instance; same shape as GroupOptions, but the name defaults to the placed definition’s name.

Traits: Clone, Debug, PartialEq, Default

Fields

struct ImageOptions

pub struct ImageOptions

Options for SkpBuilder::add_image.

Traits: Clone, Copy, Debug, Default, PartialEq

Fields

struct DefinitionHandle

pub struct DefinitionHandle

A reference to a component/group definition of one SkpBuilder, used to place it (add_instance/add_group_instance) or to reopen its ComponentDefinitionBuilder.

Traits: Clone, Copy, Debug, PartialEq, Eq, Hash

Some fields are private.

struct SkpBuilder

pub struct SkpBuilder

Accumulates geometry and writes it into a new legacy-format (v17) .skp file. Sections are spliced into the scaffold in a fixed order, so calls must follow it: materials, then layers, then component definitions/groups, then root-level geometry and placements. Each step’s archive slot numbering depends on the final size of every earlier one.

Traits: Debug, Default, ReplayTarget

Some fields are private.

Methods

fn create

pub fn create() -> SkpBuilder

Start building a new legacy-format (v17) .skp file. Same as SkpBuilder::new.

struct ComponentDefinitionBuilder

pub struct ComponentDefinitionBuilder<'a>

Accumulates one component/group definition’s geometry. Obtained from SkpBuilder::add_component_definition, SkpBuilder::add_group or SkpBuilder::definition; it borrows the builder, so finish the definition (close()) before going back to the builder - only one definition can be open at a time anyway.

let mut builder = create();
let mut chair = builder.add_component_definition("Chair", &DefinitionOptions::default())?;
chair.add_face(&[[0.0, 0.0, 0.0], [20.0, 0.0, 0.0], [20.0, 20.0, 0.0], [0.0, 20.0, 0.0]], &FaceOptions::default())?;
let chair = chair.close()?;
builder.add_instance(chair, &InstanceOptions { translation: [100.0, 0.0, 0.0], ..Default::default() })?;

Traits: Debug, ReplayTarget

Some fields are private.

Methods

cc_skp::create::archive

crates/cc_skp/src/create/archive.rs

ArchiveWriter - the write-side mirror of the legacy reader’s MFC CArchive slot/class-ref bookkeeping, plus every entity record encoder the builder uses.

Items: PutLe · read_u16_at · write_u16_at · write_u32_at · shift_ref · detect_image_subtype · IdSource · AttributeDictList · Topology · EdgeFlags · ArcCurveParams · ChainCurve · FaceSpec · TextureSource · Placement · ArchiveWriter

trait PutLe

pub(super) trait PutLe

Little-endian appends onto a byte buffer.

Implemented by (1): cc_skp::create::archive::Vec

Required and provided items

fn read_u16_at

pub(super) fn read_u16_at(buf: &[u8], pos: usize) -> u16

fn write_u16_at

pub(super) fn write_u16_at(buf: &mut [u8], pos: usize, v: u16)

fn write_u32_at

pub(super) fn write_u32_at(buf: &mut [u8], pos: usize, v: u32)

fn shift_ref

pub(super) fn shift_ref(buf: &mut Vec<u8>, pos: usize, shift: i32) -> usize

Renumber the u16 slot reference at pos by shift, keeping its 0x8000 class-ref tag bit. Widens to the 6-byte escape form if the new slot lands at or past 0x7FFF: 0x7FFF is the archive’s big-tag escape marker and 0x8000|0x7FFF == 0xFFFF its new-class marker, so neither can be an ordinary slot number. Returns how many bytes the field grew by (0 or 4).

fn detect_image_subtype

pub(super) fn detect_image_subtype(image_bytes: &[u8]) -> Result<u32, SkpWriteError>

CDib’s image format tag from the file’s own magic bytes: 4 for PNG, 1 for JPEG.

enum IdSource

pub(super) enum IdSource

Where definition/instance GUIDs and definition timestamps come from.

Traits: Clone, Debug

Variants

Methods

type alias AttributeDictList

pub(super) type AttributeDictList = Vec<(String, AttributeDict)>

A named attribute dictionary, in write order.

struct Topology

pub(super) struct Topology

The vertex/edge sharing state of one entity list (the root model or one definition).

Traits: Debug, Default

Some fields are private.

struct EdgeFlags

pub(super) struct EdgeFlags

Traits: Clone, Copy, Debug, Default

Fields

struct ArcCurveParams

pub(super) struct ArcCurveParams

Curve parameters shared by every edge of a circle/arc - see write_arc_curve.

Traits: Clone, Copy, Debug

Fields

enum ChainCurve

pub(super) enum ChainCurve<'a>

The curve object an edge chain’s edges share, declared inline by its first new edge.

Traits: Clone, Copy, Debug

Variants

struct FaceSpec

pub(super) struct FaceSpec<'a>

Everything about one face except its outer boundary points.

Traits: Clone, Copy, Debug

Fields

struct TextureSource

pub(super) struct TextureSource<'a>

A texture image to embed: its bytes, the path string stored with it, and its CDib subtype.

Traits: Clone, Copy, Debug

Fields

struct Placement

pub(super) struct Placement<'a>

One placement of a definition (component instance, group or image).

Traits: Clone, Copy, Debug

Fields

struct ArchiveWriter

pub(super) struct ArchiveWriter

Traits: Clone, Debug

Fields

Some fields are private.

Methods

cc_skp::create::geometry

crates/cc_skp/src/create/geometry.rs

Small geometry/linear-algebra helpers for the writer. Every formula keeps the exact operation order of the C++ writer: these values are written straight into the file as f64s, so any reassociation would change output bytes.

Items: cross3 · normalize3 · resolve_matrix3x3 · circle_basis · circle_points · arc_points · uv_matrix_for_face · polygon_span · plane_tolerance · Plane · newell_plane · plane_from_polygon · is_coplanar

fn cross3

pub(super) fn cross3(a: Point3, b: Point3) -> Point3

fn normalize3

pub(super) fn normalize3(v: Point3) -> Result<Point3, SkpWriteError>

fn resolve_matrix3x3

pub(super) fn resolve_matrix3x3(matrix3x3: Option<Matrix3x3>, rotation: Option<Rotation>) -> Result<Option<Matrix3x3>, SkpWriteError>

matrix3x3 and rotation are two spellings of the same transform field, so at most one may be given (neither means identity).

fn circle_basis

pub(super) fn circle_basis(normal: Point3) -> Result<(Point3, Point3), SkpWriteError>

An arbitrary orthonormal in-plane basis (U, W) for a circle/arc plane: Gram-Schmidt whichever of world +Z/+X is less parallel to normal, then W = normal x U.

fn circle_points

pub(super) fn circle_points(center: Point3, radius: f64, num_segments: u32, u: Point3, w: Point3) -> Vec<Point3>

fn arc_points

pub(super) fn arc_points(center: Point3, radius: f64, num_segments: u32, (u, w): (Point3, Point3), start_angle: f64, end_angle: f64) -> Vec<Point3>

The num_segments + 1 points (both endpoints included) of a partial arc.

fn uv_matrix_for_face

pub(super) fn uv_matrix_for_face(pairs: &[UvPoint], normal: Point3) -> Result<Matrix3x3, SkpWriteError>

Fit the 3x3 UV-to-world affine matrix real SketchUp stores for a positioned texture, from exactly 3 (world point, (u, v)) correspondences, in the face’s own UV basis.

fn polygon_span

pub(super) fn polygon_span(points: &[Point3]) -> f64

The largest axis-aligned extent of points.

fn plane_tolerance

pub(super) fn plane_tolerance(points: &[Point3]) -> f64

The coplanarity tolerance for a polygon: scales with the face’s own size.

struct Plane

pub(super) struct Plane

A plane nx*x + ny*y + nz*z = d with a unit normal.

Traits: Clone, Copy, Debug

Fields

Methods

fn newell_plane

pub(super) fn newell_plane(points: &[Point3]) -> Result<Plane, SkpWriteError>

Newell’s method: sums a cross-product-like term over every edge rather than reading the normal off the first 3 points - correct for concave polygons too, as long as the polygon is planar and simple.

fn plane_from_polygon

pub(super) fn plane_from_polygon(points: &[Point3]) -> Result<Plane, SkpWriteError>

The polygon’s plane; every point must actually lie on it.

fn is_coplanar

pub(super) fn is_coplanar(points: &[Point3]) -> Result<bool, SkpWriteError>

Same fit/tolerance as plane_from_polygon, but answers instead of failing on a non-planar polygon (still fails on a degenerate one).

cc_skp::create::scaffold_blank_v17

crates/cc_skp/src/create/scaffold_blank_v17.rs

The blank-document scaffold every new file is spliced into, and the fixed positions inside it the writer patches. scaffold_blank_v17.skp is byte-for-byte the SDK-authored empty v17 document every OpenSKP writer port bundles (packages/python/src/openskp/_scaffold/blank_v17.skp, sha256 809a1ab73a20a192ab13aaff197afb1c67d0e9352f6a353a9cd8030919f8a6c3; also tests/fixtures/blank_v17.skp). See the crate::create module docs for what it is and why it is there. The Python writer computes the offsets below at runtime by walking the scaffold with the generic MFC archive reader; since the scaffold is a fixed blob, the C++ port (and this one) bake them in instead. They were produced against the exact bundled file with:

import openskp, sys
b = sys.modules['openskp.create'].SkpBuilder()
# then print each of: b._material_insert_pos, b._base, b._layer_count_pos,
# b._orig_layer_count, b._layer_insert_pos, b._layer_writer_base, b._def_count_pos,
# b._orig_def_count, b._root_count_pos, b._orig_root_count, b._tail_pos,
# b._scaffold_next_slot, b._scaffold_class_slot
```rust
If the scaffold is ever swapped, re-run that recipe and update the file AND every constant
here together.

**Items:** [`SCAFFOLD_BLANK_V17`](#cc_skp-create-scaffold_blank_v17-scaffold_blank_v17) · [`MATERIAL_INSERT_POS`](#cc_skp-create-scaffold_blank_v17-material_insert_pos) · [`BASE`](#cc_skp-create-scaffold_blank_v17-base) · [`LAYER_COUNT_POS`](#cc_skp-create-scaffold_blank_v17-layer_count_pos) · [`ORIG_LAYER_COUNT`](#cc_skp-create-scaffold_blank_v17-orig_layer_count) · [`LAYER_INSERT_POS`](#cc_skp-create-scaffold_blank_v17-layer_insert_pos) · [`LAYER_WRITER_BASE`](#cc_skp-create-scaffold_blank_v17-layer_writer_base) · [`DEF_COUNT_POS`](#cc_skp-create-scaffold_blank_v17-def_count_pos) · [`ORIG_DEF_COUNT`](#cc_skp-create-scaffold_blank_v17-orig_def_count) · [`ROOT_COUNT_POS`](#cc_skp-create-scaffold_blank_v17-root_count_pos) · [`ORIG_ROOT_COUNT`](#cc_skp-create-scaffold_blank_v17-orig_root_count) · [`TAIL_POS`](#cc_skp-create-scaffold_blank_v17-tail_pos) · [`SCAFFOLD_NEXT_SLOT`](#cc_skp-create-scaffold_blank_v17-scaffold_next_slot) · [`PID_COUNTER_POS`](#cc_skp-create-scaffold_blank_v17-pid_counter_pos) · [`FIRST_NEW_PID`](#cc_skp-create-scaffold_blank_v17-first_new_pid) · [`TAIL_REF_POSITIONS`](#cc_skp-create-scaffold_blank_v17-tail_ref_positions) · [`ACTIVE_LAYER_ANCHOR_REL`](#cc_skp-create-scaffold_blank_v17-active_layer_anchor_rel) · [`CCAMERA_SLOT`](#cc_skp-create-scaffold_blank_v17-ccamera_slot) · [`ATTR_CONTAINER_SLOT`](#cc_skp-create-scaffold_blank_v17-attr_container_slot) · [`ATTRIBUTE_NAMED_SLOT`](#cc_skp-create-scaffold_blank_v17-attribute_named_slot) · [`ISO_CAMERA_PREFIX_OFFSET`](#cc_skp-create-scaffold_blank_v17-iso_camera_prefix_offset) · [`ISO_CAMERA_PREFIX_PATCH`](#cc_skp-create-scaffold_blank_v17-iso_camera_prefix_patch) · [`ISO_CAMERA_TAIL_PATCHES`](#cc_skp-create-scaffold_blank_v17-iso_camera_tail_patches)

<a id="cc_skp-create-scaffold_blank_v17-scaffold_blank_v17"></a>

### static `SCAFFOLD_BLANK_V17`

```rust
pub(super) static SCAFFOLD_BLANK_V17: &[u8; 5796]

The bundled blank v17 document.

const MATERIAL_INSERT_POS

pub(super) const MATERIAL_INSERT_POS: usize

Absolute offset of the material-manager insertion point (right before the “layer list marker” a zero-material scaffold starts with) - Python’s _material_insert_pos.

const BASE

pub(super) const BASE: i32

Starting archive slot for anything spliced in after the (empty) material section - _base.

const LAYER_COUNT_POS

pub(super) const LAYER_COUNT_POS: usize

Absolute offset of the u32 layer-count field that precedes the layer list.

const ORIG_LAYER_COUNT

pub(super) const ORIG_LAYER_COUNT: i32

const LAYER_INSERT_POS

pub(super) const LAYER_INSERT_POS: usize

Absolute offset right after the scaffold’s own layer records (Layer0) - where new layers go.

const LAYER_WRITER_BASE

pub(super) const LAYER_WRITER_BASE: i32

Starting archive slot for a fresh layer writer, before any material shift.

const DEF_COUNT_POS

pub(super) const DEF_COUNT_POS: usize

Absolute offset of the u32 component-definition-count field.

const ORIG_DEF_COUNT

pub(super) const ORIG_DEF_COUNT: i32

const ROOT_COUNT_POS

pub(super) const ROOT_COUNT_POS: usize

Absolute offset of the u32 root-entity-count field.

const ORIG_ROOT_COUNT

pub(super) const ORIG_ROOT_COUNT: i32

const TAIL_POS

pub(super) const TAIL_POS: usize

Absolute offset where the document “tail” (the undecoded style/font-manager region) begins.

const SCAFFOLD_NEXT_SLOT

pub(super) const SCAFFOLD_NEXT_SLOT: i32

Starting slot for anything written after the byte-for-byte-copied layer/definition/root region - _scaffold_next_slot.

const PID_COUNTER_POS

pub(super) const PID_COUNTER_POS: usize

Offset of the u64 next persistent entity id. Ids are document-wide, not per archive section; the scaffold has already consumed the ids below FIRST_NEW_PID.

const FIRST_NEW_PID

pub(super) const FIRST_NEW_PID: u64

The first persistent id free for new objects in the scaffold.

const TAIL_REF_POSITIONS

pub(super) const TAIL_REF_POSITIONS: [usize; 6]

Offsets, relative to the tail start, of internal slot references that must be renumbered by the number of archive slots inserted before them.

const ACTIVE_LAYER_ANCHOR_REL

pub(super) const ACTIVE_LAYER_ANCHOR_REL: usize

Offset (relative to the layer insertion point) of the active-layer anchor - a back-reference to Layer0. Moves only when materials shift Layer0’s own slot.

const CCAMERA_SLOT

pub(super) const CCAMERA_SLOT: i32

Classes the scaffold’s own prefix already declares, so the writer only ever short-refs them.

const ATTR_CONTAINER_SLOT

pub(super) const ATTR_CONTAINER_SLOT: i32

const ATTRIBUTE_NAMED_SLOT

pub(super) const ATTRIBUTE_NAMED_SLOT: i32

const ISO_CAMERA_PREFIX_OFFSET

pub(super) const ISO_CAMERA_PREFIX_OFFSET: usize

The scaffold ships SketchUp’s arbitrary default camera; every written file is patched to the standard “Iso” view instead (parallel projection, looking at the origin from the (1, -1, 1) octant). Found by diffing two SDK-authored blank documents that differ only in an explicit SUCameraSetOrientation + SUCameraSetPerspective(false) - copied verbatim, not decoded.

const ISO_CAMERA_PREFIX_PATCH

pub(super) const ISO_CAMERA_PREFIX_PATCH: [u8; 98]

const ISO_CAMERA_TAIL_PATCHES

pub(super) const ISO_CAMERA_TAIL_PATCHES: [(usize, &[u8]); 2]

Iso-camera patches inside the tail, as (offset relative to the tail start, bytes).

cc_skp::curves

crates/cc_skp/src/curves.rs

Loose-edge chaining and analytic-arc recovery, shared by the baked and the instanced scene builders (Python port extension: openskp/_curves.py; the C++ port has no equivalent). Loose edges - edges no face uses - are how SketchUp stores drawing geometry (a facade elevation, a section outline). Edges bounding a face are already represented by that face’s mesh and are not emitted again. The run order follows the Python reference exactly, including the iteration order of the CPython set it walks a curve’s edges from (see py_set_order), so a run comes out in the same direction there and here.

Items: INCHES_TO_M · LooseRun · round6 · py_set_order · majority_layer · chain_loose_edges · solve_run_arc

const INCHES_TO_M

pub const INCHES_TO_M: f64

Inches to metres.

struct LooseRun

pub struct LooseRun

One chained run of loose edges: its edges in walk order, the vertex ids along it, and whether it returns to its first vertex (which is then NOT repeated at the end).

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

fn round6

pub fn round6(x: f64) -> f64

Python’s round(x, 6): the double nearest the decimal rounding of x’s exact value to 6 places, ties to even.

fn py_set_order

pub fn py_set_order(keys: &[EntityId]) -> Vec<EntityId>

The iteration order of CPython’s set(keys) for integer keys (Objects/setobject.c: open addressing with 9 linear probes, then perturbed probing; the table grows 4x once 3/5 full). Duplicates keep their first occurrence.

fn majority_layer

pub(crate) fn majority_layer(ids: impl Iterator<Item = Option<EntityId>>) -> Option<EntityId>

The majority layer id (first wins a tie) among ids, ignoring absent and zero ids; None when there is none.

fn chain_loose_edges

pub fn chain_loose_edges(b: &GeometryBuilder) -> Vec<LooseRun>

Turns a definition’s loose edges into polyline runs. Grouping comes from the file (edge_curves, SketchUp’s own Edge#curve), not from vertex adjacency: an edge with no curve is its own two-point run, and two curves touching at a vertex stay two runs. Ungrouped edges come first (in edge order), then each curve in first-seen order.

fn solve_run_arc

pub fn solve_run_arc(b: &GeometryBuilder, eids: &[EntityId], matrix: Option<&[f64]>, pts: &[Vec3], closed: bool) -> Option<CurveArc>

Recovers the analytic arc behind one loose-edge run, or None (the answer for almost every run, and the safe one: the caller then keeps the chords the file stores). The frame (arc_curves) is used only if (1) the run is the whole curve, (2) the frame is a circle (y_axis == normal x x_axis, not the affine image of one), and (3) every point lies on that circle. pts are the run’s points as the caller produced them (metres, glTF Y-up, rounded to 6 places) after transforming by matrix (None = local space); the result is in the same frame. A full turn comes back as two half-turn segments.

cc_skp::deflate

crates/cc_skp/src/deflate.rs

A small pure-Rust DEFLATE (RFC 1951) / zlib (RFC 1950) compressor: hash-chain LZ77 with optional one-step lazy matching, and per block the cheapest of stored / fixed-Huffman / dynamic-Huffman coding. Output is valid DEFLATE but not byte-identical to miniz’s tdefl.

Items: deflate_raw · zlib_compress

fn deflate_raw

pub fn deflate_raw(data: &[u8], level: u32) -> Vec<u8>

Compresses data into a raw DEFLATE stream. level 0 stores; 1-10 trade speed for ratio (longer hash chains, lazy matching from 4).

fn zlib_compress

pub fn zlib_compress(data: &[u8], level: u32) -> Vec<u8>

Compresses data into a zlib stream (2-byte header, DEFLATE, Adler-32).

cc_skp::earcut

crates/cc_skp/src/earcut.rs

2D ear-clipping with holes (earcut.cpp): EarPoint and earcut_2d. Every holeless loop is clipped directly; each hole is bridged into the outer boundary from its right-most vertex to the nearest boundary vertex on its right. When two or more holes genuinely overlap, bridging them independently can produce a self-intersecting ring, so the outer boundary is clipped alone and triangles whose centroid falls inside any hole are dropped instead (openskp#285).

Items: EarPoint · MAX_EAR_VERTICES · MAX_CLIP_WORK · earcut_2d

struct EarPoint

pub struct EarPoint

One projected 2D vertex, tagged with the source vertex id.

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

const MAX_EAR_VERTICES

pub const MAX_EAR_VERTICES: usize

Most vertices (all loops of a face) ear clipped; a larger face is fanned from the first vertex of its outer loop instead, its holes left out (exact for convex outlines, and bounded for any): checking holes for overlaps and clipping cost the square of the vertices or more.

const MAX_CLIP_WORK

pub const MAX_CLIP_WORK: usize

Most steps (vertices looked at, ear tests, vertices shifted) one ring is clipped with; what is left past them is fanned.

fn earcut_2d

pub fn earcut_2d(mut loops: Vec<Vec<EarPoint>>) -> Vec<[EntityId; 3]>

Triangulates loops[0] (outer boundary) minus loops[1..] (holes), returning vertex-id triples.

cc_skp::edit

crates/cc_skp/src/edit.rs

Load an existing legacy-format .skp file and rebuild it as a new, independent SkpBuilder (edit.hpp / edit.cpp, itself a port of Python’s openskp.edit). create only ever builds a brand-new file by splicing new geometry into its own bundled blank scaffold - there is no way to append to or patch an arbitrary existing file’s bytes in place, because real SketchUp itself doesn’t do that either: it fully re-serializes the whole document on every save, so there is no stable “original bytes + appended bytes” structure to target for a file this project didn’t create. This module takes the other viable approach instead: fully parse the existing file with this crate’s own reader, then replay everything it understood back through the create public API (materials, layers, every component definition, every face/instance, construction points and lines) to produce a brand-new file - not a byte-patched copy of the original, but a freshly-built one with equivalent content, to which the caller can add more geometry before saving. Adding more geometry after the fact. The returned builder can take more add_face/ add_circle/add_instance/etc. calls, and every material/layer the source had is already reachable via SkpBuilder::materials_by_name/SkpBuilder::layers_by_name; OpenExistingResult::definitions maps each component definition’s name to its handle, for placing more instances of something the source already defined. What the returned builder can no longer do is register a genuinely NEW material, layer, or component definition/group - the writer’s own file-format ordering requirement (materials/layers/definitions must all be finalized before any geometry is written) is already satisfied by the time replay finishes writing the source’s own root-level geometry (which happens for any source file with root-level content - in practice, almost always), so add_material/add_layer/ add_component_definition/add_group all fail with SkpWriteError on the returned builder in that case. Build anything new into a separate create() call instead. Scope and known fidelity gaps (every gap here is a genuine, deliberately-scoped limitation carried over from the Python port, not an oversight):

Items: OpenExistingResult · OpenExistingError · EdgeMap · build_edge_map · reconstruct_loop_vertices · face_uv_basis · texture_suffix · non_collinear_triple · open_existing

struct OpenExistingResult

pub struct OpenExistingResult

Result of open_existing.

Traits: Debug

Fields

enum OpenExistingError

pub enum OpenExistingError

Why open_existing failed. The C++ port throws one of two exception types; this keeps them apart.

Traits: Debug, fmt::Display, Error, From<SkpWriteError>, From<SkpParseError>

Variants

type alias EdgeMap

pub(crate) type EdgeMap = BTreeMap<EntityId, (EntityId, EntityId)>

fn build_edge_map

pub(crate) fn build_edge_map(defn: &Definition) -> EdgeMap

fn reconstruct_loop_vertices

pub(crate) fn reconstruct_loop_vertices(lp: &[CoEdge], edges: &EdgeMap) -> Vec<EntityId>

fn face_uv_basis

pub(crate) fn face_uv_basis(n: Point3) -> (Point3, Point3)

fn texture_suffix

pub(crate) fn texture_suffix(filename: &str) -> &str

The image’s file-name suffix (from the last .), .png if there is none.

fn non_collinear_triple

pub(crate) fn non_collinear_triple(points: &[Point3]) -> Option<[Point3; 3]>

front_uv/back_uv need exactly 3 correspondences whose (u, v) values are NOT collinear (an affine fit is impossible otherwise) - real faces can have a “flat” vertex (three consecutive vertices genuinely collinear in 3D), which points[0..2] alone isn’t guaranteed to avoid. Search for the first non-collinear triple - an affine map preserves collinearity, so a non-collinear triple in 3D is also non-collinear in (u, v).

fn open_existing

pub fn open_existing(path: impl AsRef<Path>) -> Result<OpenExistingResult, OpenExistingError>

Parse path (a legacy-format .skp file) and rebuild it as a new SkpBuilder, replaying materials, layers, every component definition, and all root-level geometry/instances. See the module docs for exactly what is and isn’t reproduced. Fails with OpenExistingError::Write if path can’t be read or isn’t a legacy-format file (or replay fails), and with OpenExistingError::Parse if the reader rejects it.

cc_skp::errors

crates/cc_skp/src/errors.rs

Structured parse errors (errors.hpp / errors.cpp).

Items: ErrorCause · SkpParseError · Result

type alias ErrorCause

pub type ErrorCause = Arc<dyn Error + Send + Sync + 'static>

The underlying error an SkpParseError wraps (C++’s std::exception_ptr).

struct SkpParseError

pub struct SkpParseError(Box<Inner>)

A parse failure with optional context: the pipeline stage, the record being processed, its tag/offset, the definition, and the underlying cause. Display renders the same text as the C++ what(): message | stage=... | record=r/t | tag=... | offset=0x... | definitionId=....

Traits: Clone, fmt::Display, fmt::Debug, Error

Methods

type alias Result

pub type Result<T, E = SkpParseError> = std::result::Result<T, E>

Crate-wide result alias.

cc_skp::face_groups

crates/cc_skp/src/face_groups.rs

Local-space face grouping shared by the baked (scene_build.rs) and instanced (instanced_scene_build.rs) scene builders (face_groups.hpp / face_groups.cpp). A definition’s faces are grouped by resolved (color, double_sided, texture) identity in DEFINITION-LOCAL space (inches, SketchUp Z-up): exactly what the baked builder assembles just before applying an instance’s world matrix, and exactly what the instanced builder keeps local and puts on the node instead. One implementation keeps the two paths agreeing on triangulation, UV seams, normals and front/back handling. An unpainted face falls back to the caller’s fallback_color for color, but its material (and so its texture tile size) comes from the face’s OWN material_id / back_material_id only. The color key carries a 4th (alpha) component.

Items: FaceColorKey · GroupKey · FaceVKey · Group · find_material · material_color · default_color · sniff_image_mime · TextureRegistry · FaceGroupContext · build_local_face_groups

type alias FaceColorKey

pub type FaceColorKey = [i32; 4]

Color key: (r, g, b, alpha-from-transparency).

struct GroupKey

pub struct GroupKey

A face group’s identity. Ordered like the C++ std::tie(color, double_sided, texture_index) (an absent texture sorts first).

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default

Fields

type alias FaceVKey

pub type FaceVKey = (EntityId, u64, u64)

A vertex is keyed by (source vertex id, u, v): UVs are per-face, so a position shared by two faces that disagree on texture mapping becomes two output vertices. The doubles are stored as bits with -0.0 folded into 0.0, matching the C++ std::map’s < equivalence.

struct Group

pub struct Group

One group’s local-space mesh. verts, uvs and normals (accumulated, unnormalised) are aligned by output vertex index.

Traits: Debug, Clone, PartialEq, Default

Fields

fn find_material

pub fn find_material(parsed: &RawParsed, id: Option<EntityId>) -> Option<&RawMaterial>

The material a face (or instance) material id names: by name first, then by material folder.

fn material_color

pub fn material_color(material: Option<&RawMaterial>) -> Option<FaceColorKey>

A material’s color key. Opacity combines the RGBA color record’s alpha byte and the XML material’s transparency; the untouched one defaults to fully opaque.

fn default_color

pub fn default_color(parsed: &RawParsed, layer: &str) -> FaceColorKey

The layer’s color (or SketchUp’s default grey), fully opaque.

fn sniff_image_mime

pub fn sniff_image_mime(data: &[u8]) -> Option<&'static str>

An image’s MIME type from its magic bytes; None for anything glTF cannot carry (glTF only allows PNG and JPEG).

struct TextureRegistry

pub struct TextureRegistry

The scene’s texture table, deduplicated by bytes (the builders’ texture_index_for): the same image routinely backs several materials.

Traits: Debug, Clone, Default

Fields

Some fields are private.

Methods

struct FaceGroupContext

pub struct FaceGroupContext<'a>

What build_local_face_groups needs from its caller besides the builder.

Fields

fn build_local_face_groups

pub fn build_local_face_groups(parsed: &RawParsed, b: &GeometryBuilder, ctx: &mut FaceGroupContext<'_>) -> Result<BTreeMap<GroupKey, Group>, Error>

Groups a definition’s faces by resolved material identity, in local space. A face whose front and back resolve to the SAME color is emitted once with double_sided set; a face whose sides differ is emitted as two single-sided triangle sets (one normal-wound front, one reverse-wound back) so each side keeps its own color. Fails (OutOfRange, the C++ map::at) when a triangle references a vertex the builder does not have.

cc_skp::inflate

crates/cc_skp/src/inflate.rs

Pure-Rust DEFLATE (RFC 1951) and zlib (RFC 1950) decoder, replacing the parts of miniz’s tinfl / mz_uncompress the reader uses. Validation follows tinfl: a Huffman code must be complete unless it uses at most one symbol, a length-repeat code may not start the code-length list, a distance may not reach before the start of the output, and a stored block’s LEN must match ~NLEN. Output can be capped; exceeding the cap is an error (tinfl’s non-wrapping output buffer).

Items: InflateError · inflate_raw · adler32 · zlib_decompress · zlib_decompress_capped · UncompressError · uncompress

enum InflateError

pub enum InflateError

Why a stream failed to decode.

Traits: Debug, Clone, Copy, PartialEq, Eq, fmt::Display, std::error::Error

Variants

fn inflate_raw

pub fn inflate_raw(input: &[u8], limit: usize) -> Result<Vec<u8>, InflateError>

Decodes a raw DEFLATE stream (no zlib wrapper). Fails with InflateError::OutputLimit when the output would exceed limit bytes.

fn adler32

pub fn adler32(data: &[u8]) -> u32

Adler-32 checksum.

fn zlib_decompress

pub fn zlib_decompress(input: &[u8]) -> Result<Vec<u8>, InflateError>

Decodes a complete zlib stream (RFC 1950), verifying the Adler-32 trailer. The output size is not limited: a small hostile stream can expand to gigabytes. Use this only on input you trust (for example, data you just compressed yourself); for untrusted input use zlib_decompress_capped. The library itself never calls this on file data.

fn zlib_decompress_capped

pub fn zlib_decompress_capped(input: &[u8], limit: usize) -> Result<Vec<u8>, InflateError>

Decodes a complete zlib stream (RFC 1950) up to limit uncompressed bytes, verifying the Adler-32 trailer.

enum UncompressError

pub enum UncompressError

Result codes of uncompress, mirroring mz_uncompress.

Traits: Debug, Clone, Copy, PartialEq, Eq, fmt::Display, std::error::Error

Variants

fn uncompress

pub fn uncompress(src: &[u8], dest_cap: usize) -> Result<Vec<u8>, UncompressError>

mz_uncompress equivalent: decodes a zlib stream into at most dest_cap bytes. A too-small destination is UncompressError::Buf (callers grow and retry); anything else that fails is UncompressError::Data.

cc_skp::instanced_scene

crates/cc_skp/src/instanced_scene.rs

The instanced scene graph (instanced_scene.hpp). Types only; the builder lives in instanced_scene_build.rs.

Items: LocalPrimitive · InstancedMeshResource · LocalCurve · InstancedCurveResource · IDENTITY_GLTF · InstancedNode · SceneBounds · InstancedScene

struct LocalPrimitive

pub struct LocalPrimitive

One reusable, DEFINITION-LOCAL triangulated mesh: the instanced counterpart of GlbPrimitive, minus the world transform (metres, glTF Y-up). Normal transformation is deferred to the consumer’s node transform.

Traits: Debug, Clone, PartialEq, Default

Fields

struct InstancedMeshResource

pub struct InstancedMeshResource

A definition’s geometry resolved for one rendering context. One definition can yield more than one resource (e.g. painted two colors) - see variant_key.

Traits: Debug, Clone, PartialEq, Default

Fields

struct LocalCurve

pub struct LocalCurve

One loose-edge run in definition-local space (Python port extension).

Traits: Debug, Clone, PartialEq, Default

Fields

struct InstancedCurveResource

pub struct InstancedCurveResource

A definition’s loose edges, ready to be referenced by any number of nodes - the loose-edge counterpart of InstancedMeshResource (Python port extension).

Traits: Debug, Clone, PartialEq, Default

Fields

const IDENTITY_GLTF

pub const IDENTITY_GLTF: [f64; 16]

The glTF identity matrix.

struct InstancedNode

pub struct InstancedNode

One placed node in the instanced scene graph.

Traits: Debug, Clone, PartialEq, Default

Fields

struct SceneBounds

pub struct SceneBounds

Axis-aligned bounds of the scene as PLACED, metres and Y-up.

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

struct InstancedScene

pub struct InstancedScene

The result of build_instanced_scene(): the placed scene graph with SketchUp’s instancing PRESERVED.

Traits: Debug, Clone, PartialEq, Default

Fields

cc_skp::instanced_scene_build

crates/cc_skp/src/instanced_scene_build.rs

The instanced scene builder (instanced_scene.cpp’s build_instanced_scene_raw), plus the Python port’s loose-edge curve resources (instanced_scene.py’s curve_resources).

Items: build_instanced_scene_raw

fn build_instanced_scene_raw

pub fn build_instanced_scene_raw(mut p: RawParsed, o: &ParseOptions) -> Result<InstancedScene, SkpParseError>

Builds the instanced scene graph from a reader’s raw output.

cc_skp::internal

crates/cc_skp/src/internal/mod.rs

Reader infrastructure shared by the VFF reader, the legacy reader and the scene builders (internal.hpp). Public (but #[doc(hidden)] from the crate root) so integration tests and sibling modules can reach the same internals the C++ tests include.

Re-exports

Items: ErrorKind · Error · Result · Tag · TlvNode · RawFace · RawInstance · RawArcFrame · GeometryBuilder · RawDefinition · RawTexture · RawMaterial · RawStyle · RawPage · RawDimension · RawCamera · RawParsed · text · hex_upper

enum ErrorKind

pub enum ErrorKind

Which standard exception the C++ code would have thrown.

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash

Variants

struct Error

pub struct Error

An internal failure: a bounds-checked read past the end, a varint wider than 64 bits, or a reader giving up (std::runtime_error). Readers return it; the parse entry points wrap it into an SkpParseError cause.

Traits: Debug, Clone, PartialEq, Eq, fmt::Display, std::error::Error

Fields

Methods

type alias Result

pub type Result<T, E = Error> = std::result::Result<T, E>

Result of an internal reader step.

struct Tag

pub struct Tag([u8; 4])

A TLV tag as its 4 upper-case hex digits in byte order (bytes F4 01 are "F401"), stored inline. Compares directly against &str.

Traits: Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, From<&str>, PartialEq<str>, PartialEq<&str>, fmt::Display, fmt::Debug

Methods

struct TlvNode

pub struct TlvNode

One TLV record: container tags carry children, everything else (and a container whose payload does not parse) carries payload.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

Methods

struct RawFace

pub struct RawFace

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawInstance

pub struct RawInstance

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawArcFrame

pub struct RawArcFrame

The analytic frame of a Curve that is one arc.

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

struct GeometryBuilder

pub struct GeometryBuilder

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawDefinition

pub struct RawDefinition

Traits: Debug, Clone, PartialEq, Default

Fields

Methods

struct RawTexture

pub struct RawTexture

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawMaterial

pub struct RawMaterial

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawStyle

pub struct RawStyle

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct RawPage

pub struct RawPage

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawDimension

pub struct RawDimension

Traits: Debug, Clone, PartialEq, Default

Fields

struct RawCamera

pub struct RawCamera

A view camera record (34BC), as scenes and the model’s current view store it.

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

struct RawParsed

pub struct RawParsed

Everything a reader (VFF or legacy) extracts, before build_model / build_scene_raw / build_instanced_scene_raw shape it.

Traits: Debug, Clone, PartialEq, Default

Fields

fn text

pub fn text(p: &[u8]) -> String

Lossy UTF-8 text of raw bytes (the C++ keeps them as a byte string).

fn hex_upper

pub fn hex_upper(p: &[u8]) -> String

Upper-case hex of raw bytes.

cc_skp::internal::build_model

crates/cc_skp/src/internal/build_model.rs

Shapes a RawParsed into the public SkpModel (model.cpp’s build_model).

Items: build_model

fn build_model

pub fn build_model(p: RawParsed, o: &ParseOptions) -> SkpModel

Builds the public model from a reader’s raw output.

cc_skp::internal::bytes

crates/cc_skp/src/internal/bytes.rs

Bounds-checked little-endian readers, var-ints and the TLV walkers (tlv.cpp).

Items: read_u16 · read_u32 · read_i32 · read_f64 · parse_varint · tag_at · u32_at · MAX_TLV_DEPTH · parse_tlv_recursive · parse_flat

fn read_u16

pub fn read_u16(d: &[u8], o: usize) -> Result<u16>

fn read_u32

pub fn read_u32(d: &[u8], o: usize) -> Result<u32>

fn read_i32

pub fn read_i32(d: &[u8], o: usize) -> Result<i32>

fn read_f64

pub fn read_f64(d: &[u8], o: usize) -> Result<f64>

fn parse_varint

pub fn parse_varint(d: &[u8], o: usize, n: usize) -> Result<u64>

Little-endian unsigned integer of n bytes (at most 8).

fn tag_at

pub fn tag_at(d: &[u8], o: usize) -> Result<Tag>

The tag of the two bytes at o, as upper-case hex in byte order.

fn u32_at

pub(crate) fn u32_at(d: &[u8], o: usize) -> u32

Infallible little-endian u32 for offsets already range-checked.

const MAX_TLV_DEPTH

pub const MAX_TLV_DEPTH: usize

Maximum allowed nesting depth for recursive container TLV nodes.

fn parse_tlv_recursive

pub fn parse_tlv_recursive(d: &[u8], start: usize, end: usize) -> Result<Vec<TlvNode>>

Parses d[start..end] into TLV nodes, recursing into container tags.

fn parse_flat

pub fn parse_flat(d: &[u8]) -> Vec<(Tag, &[u8])>

One flat level of TLV records over the whole buffer, stopping at the first record that would run past the end. Payloads borrow from d.

cc_skp::internal::core

crates/cc_skp/src/internal/core.rs

The VFF (2021+) reader: ZIP container, material/style XML, and the model.dat record walk (core.cpp).

Items: MAX_MODEL_ENTRY_BYTES · MAX_OTHER_ENTRY_BYTES · MAX_TOTAL_EXTRACTED_BYTES · decode_xml_entities · decode_xml_entities_bytes · PARSE_STACK_BYTES · full_parse

const MAX_MODEL_ENTRY_BYTES

pub const MAX_MODEL_ENTRY_BYTES: u64

Largest model.dat.

const MAX_OTHER_ENTRY_BYTES

pub const MAX_OTHER_ENTRY_BYTES: u64

Largest other entry (a texture, a style, the metadata).

const MAX_TOTAL_EXTRACTED_BYTES

pub const MAX_TOTAL_EXTRACTED_BYTES: u64

Most bytes extracted from one file’s entries in all.

fn decode_xml_entities

pub fn decode_xml_entities(value: &str) -> String

Decodes the 5 predefined XML entities plus numeric character references (&#39;, &#x27;) in a raw attribute value extracted without a real XML parser. A real material name legitimately contains “<”/”>” - SketchUp’s own “<auto>” default-material naming - so without this such names come through still escaped. A single left-to-right pass, not five sequential replacements: sequential replacement would double-decode “&lt;” into “<” instead of the correct “<”.

fn decode_xml_entities_bytes

pub fn decode_xml_entities_bytes(v: &[u8]) -> Vec<u8>

decode_xml_entities on raw bytes. Numeric references are UTF-8 encoded with the C++’s byte arithmetic (a 64-bit unsigned long); one that overflows is left as-is.

const PARSE_STACK_BYTES

pub const PARSE_STACK_BYTES: usize

Stack of the thread a parse runs on. The readers recurse up to their depth limits (legacy objects nest 256 deep), which a hostile file reaches: an optimized build needs more than the 1 MiB of the Windows main thread there and a debug build more than 8 MiB. The stack is reserved, not committed, so a large one costs only address space.

fn full_parse

pub fn full_parse(data: &[u8], o: &ParseOptions) -> Result<RawParsed, SkpParseError>

Reads a whole .skp buffer: legacy (pre-2021) files go to the legacy reader, VFF files are read here. The parse runs on its own thread with a PARSE_STACK_BYTES stack, so the caller’s stack size does not matter.

cc_skp::internal::geometry

crates/cc_skp/src/internal/geometry.rs

VFF geometry, layer, material-id and definition collection (geometry.cpp).

Items: find_node · entity_id · extract_attribute_dictionaries · collect_geometry · collect_layers · collect_model_attribute_dictionaries · collect_material_ids · collect_definitions

fn find_node

pub(crate) fn find_node<'a>(ns: &'a [TlvNode], t: &str) -> Option<&'a TlvNode>

Depth-first search for the first node tagged t.

fn entity_id

pub(crate) fn entity_id(n: &TlvNode) -> Result<Option<EntityId>>

The node’s entity id: a direct DE05 child, a DC05 child wrapping a DE05, or (failing both) the first one found deeper down.

fn extract_attribute_dictionaries

pub fn extract_attribute_dictionaries(p: &[u8], out: &mut ParsedAttrDictionaries)

Every attribute dictionary in a DC05 payload, keyed by the dictionary’s own declared name (B436). Each dictionary is a B436 name node immediately followed by a sibling entries container (typically B536) holding B636 key / A438 value pairs; B436 can occur at any depth reachable through container tags, so both walks recurse into every container-tagged node.

fn collect_geometry

pub fn collect_geometry(es: &[TlvNode], b: &mut GeometryBuilder) -> Result<()>

Collects vertices, edges, curves, faces, instances and construction geometry from a list of nodes into b, descending into any other node with children.

fn collect_layers

pub fn collect_layers(ns: &[TlvNode], out: &mut BTreeMap<EntityId, String>, hidden: &mut BTreeMap<String, bool>) -> Result<()>

Layer ids -> names and visibility from every 993A layer-manager list.

fn collect_model_attribute_dictionaries

pub fn collect_model_attribute_dictionaries(model: &TlvNode, out: &mut ParsedAttrDictionaries)

The model record (F601) carries the model entity’s own attributes the same way an instance does: an 8813 entity base holding a D007 container whose DC05 payload lists the named dictionaries.

fn collect_material_ids

pub fn collect_material_ids(ns: &[TlvNode], out: &mut BTreeMap<EntityId, String>) -> Result<()>

Material ids -> names (C832 records: DC05 id, CC32 name).

fn collect_definitions

pub fn collect_definitions(ns: &[TlvNode], out: &mut BTreeMap<EntityId, RawDefinition>) -> Result<()>

Component/group definitions (7C15 records) with their geometry.

cc_skp::internal::pages_dimensions

crates/cc_skp/src/internal/pages_dimensions.rs

VFF (2021+) scenes (“pages”) and linear dimensions (pages_dimensions.cpp, itself a port of Python’s _core.py).

Items: scan_vertex_positions · scan_instance_transforms · parse_dimensions · find_page_node · parse_camera · parse_pages

fn scan_vertex_positions

pub fn scan_vertex_positions(top: &TlvNode, id2pos: &mut BTreeMap<String, Vec3>)

Accumulates every vertex’s persistent id (hex) -> (x, y, z) inches. A vertex is a C409 record: DC05 holds its persistent id (the DE05 var-int payload), C509 its 3xf64 position. Dimension connection points reference geometry by this id. Called once per top-level record.

fn scan_instance_transforms

pub fn scan_instance_transforms(top: &TlvNode, world: &mut BTreeMap<String, Vec<f64>>)

Accumulates each instance’s persistent id (hex) -> its WORLD transform (a 13-double matrix, or empty for the identity), composing parent x local at every 6419. A dimension connects to geometry INSIDE a placed component; the vertex position is definition-local, so it must be lifted to world by the instance’s transform.

fn parse_dimensions

pub fn parse_dimensions(model_dat: &[u8], id2pos: &BTreeMap<String, Vec3>, inst_world: &BTreeMap<String, Vec<f64>>) -> Vec<RawDimension>

Linear dimensions (SketchUp’s Dimension tool). A dimension entity is a 5BCC record (raw bytes cc 5b) holding:

fn find_page_node

pub fn find_page_node(top: &TlvNode) -> Option<&TlvNode>

The 0702 scenes node inside top’s subtree (including top itself).

fn parse_camera

pub fn parse_camera(record: &[u8]) -> RawCamera

A view camera (34BC): 34BD eye, 34BE target, 34BF up (3xf64, inches), 34C4 field of view (degrees), 34C2 u8 = PERSPECTIVE flag (00 = parallel projection - calibrated against the bundled scene thumbnails), 34C3 f64 = visible height when parallel (inches). Scenes and the model’s current view (FA01) use the same record.

fn parse_pages

pub fn parse_pages(node: Option<&TlvNode>) -> Result<Vec<RawPage>>

Scenes (“pages”). The 0702 node’s payload nests 6D60 > 6D61 > one 7148 record per page:

cc_skp::internal::strconv

crates/cc_skp/src/internal/strconv.rs

C library string-to-number conversions with the C++ std::stoi / std::stoll / std::stod semantics the reader relies on: leading whitespace is skipped, the longest valid prefix is converted, trailing text is ignored, and “no conversion” or “out of range” is None (where the C++ would throw).

Items: c_stoll · c_stoi · c_stoul_digits · c_stod

fn c_stoll

pub fn c_stoll(s: &str) -> Option<i64>

std::stoll.

fn c_stoi

pub fn c_stoi(s: &str) -> Option<i32>

std::stoi.

fn c_stoul_digits

pub fn c_stoul_digits(digits: &[u8], base: u32) -> Option<u64>

std::stoul on a digit string in base (10 or 16), with a 64-bit unsigned long.

fn c_stod

pub fn c_stod(s: &str) -> Option<f64>

std::stod: decimal, hexadecimal (0x1.8p3), inf/infinity and nan prefixes; overflow and underflow (a non-zero value that rounds to zero or to a subnormal) are range errors.

cc_skp::internal::transforms

crates/cc_skp/src/internal/transforms.rs

Instance transform helpers (transforms.cpp). Matrices are the 13-value form: 0-8 the row-major 3x3, 9-11 the translation, 12 the scale term.

Items: transform_determinant · fold_scale · transform_point · transform_normal · multiply_matrices

fn transform_determinant

pub fn transform_determinant(m: &[f64]) -> f64

fn fold_scale

pub fn fold_scale(m: &[f64]) -> Vec<f64>

Folds a 13-value matrix’s scale term (index 12) into its rotation and translation, so index 12 is 1. SketchUp can keep a uniform scale in the transformation’s homogeneous term: the 3x3 stays as it is, the translation is in the scaled units, and the 16th value w is the divisor. The 13-value matrix stores 1/w at index 12, so a point transforms as s * (R p + t) with s = m[12]; folding gives the equivalent (s R) p + s t with s = 1, which every consumer that reads only indices 0-11 handles correctly (openskp#444). A matrix whose scale is already 1 is returned unchanged.

fn transform_point

pub fn transform_point(matrix: &[f64], p: Vec3) -> Vec3

fn transform_normal

pub fn transform_normal(m: &[f64], n: Vec3) -> Vec3

Transforms a normal by the inverse transpose (the cofactor matrix, with the determinant’s sign so mirrors keep normals pointing outward).

fn multiply_matrices

pub fn multiply_matrices(a: &[f64], b: &[f64]) -> Vec<f64>

a x b (apply b, then a), with both scale terms folded in first so the product’s own scale term is 1.

cc_skp::internal::vff

crates/cc_skp/src/internal/vff.rs

Header, version and meta.dat helpers (vff.cpp).

Items: valid_header · extract_version · read_meta_units · is_legacy

fn valid_header

pub fn valid_header(d: &[u8]) -> bool

The SKP magic: FF FE FF 0E.

fn extract_version

pub fn extract_version(d: &[u8]) -> String

The {major.minor.build} version string from the UTF-16 header, or "unknown".

fn read_meta_units

pub fn read_meta_units(meta_bytes: &[u8]) -> Option<String>

The model’s unit-system string from a VFF file’s meta/meta.dat contents, or None if the expected tags aren’t found.

fn is_legacy

pub fn is_legacy(d: &[u8]) -> bool

True for a classic (pre-2021, MFC) file: major version <= 20.

cc_skp::internal::xml

crates/cc_skp/src/internal/xml.rs

Hand-written equivalents of the std::regex patterns core.cpp uses to pull attributes out of material.xml / style.xml. Each function documents the pattern it reproduces and follows ECMAScript leftmost-first backtracking semantics (\s = space, \t, \n, \v, \f, \r; \w = [A-Za-z0-9_]). Everything works on bytes, like the C++ std::strings.

Items: OpenTag · find_open_tag · Element · find_element · find_screenimage · attr · attributes

struct OpenTag

pub struct OpenTag

A match of an opening-tag pattern.

Fields

fn find_open_tag

pub fn find_open_tag(s: &[u8], from: usize, name: &str, require_gt: bool) -> Option<OpenTag>

<(?:P:)?NAME\b([^>]*)> (icase) searched from from. With require_gt = false the pattern is <(?:P:)?NAME\b([^>]*) (no closing >), as material_xml’s image lookup uses.

struct Element

pub struct Element

A match of an element pattern.

Fields

fn find_element

pub fn find_element(s: &[u8], from: usize, name: &str) -> Option<Element>

<(?:P:)?NAME\b([^>]*)>([\s\S]*?)</(?:P:)?NAME> (icase) from from.

fn find_screenimage

pub fn find_screenimage(s: &[u8], from: usize) -> Option<Element>

<(?:P:)?screenimage\b([^>]*?)(?:/>|>([\s\S]*?)</(?:P:)?screenimage>) (icase) from from: a self-closing tag or one with a body.

fn attr

pub fn attr(s: &[u8], key: &str) -> String

(?:^|\s)KEY\s*=\s*["']([^"']*)["'] (icase), entity-decoded; "" when absent (core.cpp’s attr).

fn attributes

pub fn attributes(s: &[u8]) -> BTreeMap<String, String>

Every name="value" / name='value' attribute (([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')), entity-decoded; later duplicates win.

cc_skp::legacy

crates/cc_skp/src/legacy/mod.rs

Legacy (pre-2021 MFC CArchive) reader: SketchUp 3 through 2020 (legacy.cpp). A classic .skp is one MFC object graph: every object is written in full the first time anything points at it and back-referenced by its store-map slot afterwards. The walk starts at the material manager (or, with no materials, at the layer list), recovers the archive’s absolute slot base, then reads materials, layers, component definitions and the root entity list in file order. Scenes are read from the document tail afterwards. Beyond the C++ reader this port also surfaces what the Python reader does (legacy.py): each edge’s own layer (GeometryBuilder::edge_layers), each face’s raw layer id (RawFace::layer_id) and attribute values with their full SketchUp type (Time, Length, Point3d, Vector3d, nested Array).

Re-exports

Items: legacy_instance_has_guid · FIRST_V4 · FIRST_DIB_OBJECT · FIRST_NAMED_INSTANCE · LegacyKind · LegacyDimension · LegacyValue · LegacyObject · LegacySlotEntry · LegacySlotTable · LegacyPathResult · anchored_text_connection · LegacyEntityListResult · read_legacy_entity_list · legacy_connection_paths · MAX_V20_FILLER_PAD · V20FillerHit · find_count_after_v20_filler · find_empty_root_after_v20_filler · find_v20_filler_marker · read_legacy_attribute_value · parse_legacy

fn legacy_instance_has_guid

pub fn legacy_instance_has_guid(ver: i32) -> bool

const FIRST_V4

pub(crate) const FIRST_V4: i32

const FIRST_DIB_OBJECT

pub(crate) const FIRST_DIB_OBJECT: i32

const FIRST_NAMED_INSTANCE

pub(crate) const FIRST_NAMED_INSTANCE: i32

enum LegacyKind

pub enum LegacyKind

Which entity a decoded LegacyValue is (C++ V::k).

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash, Default

Variants

struct LegacyDimension

pub struct LegacyDimension

One decoded entity of the MFC object graph (C++ V): material, layer, component, edge, face, … - k says which, and only the fields that kind uses are filled. A legacy dimension’s decoded geometry, and the raw refs of its connection points, resolved to vertex positions once the whole archive is read.

Traits: Debug, Clone, PartialEq, Default

Fields

struct LegacyValue

pub struct LegacyValue

Traits: Debug, Clone, PartialEq, Default

Fields

struct LegacyObject

pub struct LegacyObject

One object read off the archive (C++ tuple<slot, class name, V>): a null reference has an empty name; a back-ref into the unwalked pre-model region is named "premodel", one into a burned connection-point band "reserved".

Traits: Debug, Clone, PartialEq

Fields

Methods

struct LegacySlotEntry

pub struct LegacySlotEntry

One legacy MFC archive slot-table entry: either a class declaration (cls, name/schema identify the class, v unused) or a read object (v holds its decoded value, possibly None for object kinds this port doesn’t decode). Public so scan_pages_for_layers is unit-testable without the full archive type.

Traits: Debug, Clone, PartialEq, Default

Fields

struct LegacySlotTable

pub struct LegacySlotTable<'a>

A minimal view into an archive’s slot-table bookkeeping - the only pieces the page (scene) scanner needs. The real reader wraps its own archive’s tables; a test can hand-build just the entries a case needs.

Fields

Methods

struct LegacyPathResult

pub struct LegacyPathResult

What follows a legacy linear dimension’s connection ref (openskp#384 / #412): [entity ref][u32 n1][n1 refs][u32 n2][n2 refs] - the instance paths of the anchored entity.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

fn anchored_text_connection

pub(crate) fn anchored_text_connection(d: &[u8], pos: usize) -> bool

Whether the text whose font ends at pos is anchored to an entity: after the two screen-fraction f64s comes the connection block, [u32 type][u32 4] [point3d], and a type other than 0 or 1 (2, 4, 5 and 7 seen; see docs/dimension-record-notes.md) anchors the label. Matches Python’s _anchored_connection.

struct LegacyEntityListResult

pub struct LegacyEntityListResult

A legacy definition’s entity list, read by read_legacy_entity_list: each item’s slot and class name, and the offset just past the list.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

fn read_legacy_entity_list

pub fn read_legacy_entity_list(data: &[u8], pos: usize, ver: i32, count: u32, table: LegacySlotTable) -> Result<LegacyEntityListResult>

Reads a legacy definition’s entity list of count items at pos, with an archive of SketchUp version ver over slots. Exposed, like scan_pages_for_layers, so the list’s bookkeeping is unit-testable: an instance a text label’s connection path writes in full is one of the list’s items whether or not the list names it again.

fn legacy_connection_paths

pub fn legacy_connection_paths<F>(data: &[u8], pos: usize, mut read_new_object: F) -> Result<LegacyPathResult> where F: FnMut(usize) -> Result<(u64, usize)>

Reads a dimension connection’s instance paths from pos. read_new_object(at) is called for a path entry MFC wrote in full (the first time anything pointed at it) and returns (slot, position just past the object). A dimension on loose geometry has a null ref and two empty lists (ten zero bytes, which the old fixed 42/82-byte blocks skipped); one anchored to a vertex inside nested components carries a ref per component, and a fixed-size read slid off the record by exactly those refs - silently truncating the ROOT entity list after it. Matches Python’s _connection_paths (openskp#384; found again on a real SketchUp 2017 cabinet, #412).

const MAX_V20_FILLER_PAD

pub(crate) const MAX_V20_FILLER_PAD: usize

struct V20FillerHit

pub struct V20FillerHit

Result of find_count_after_v20_filler: the recovered count and the offset just past it.

Traits: Debug, Clone, Copy, PartialEq, Eq

Fields

fn find_count_after_v20_filler

pub fn find_count_after_v20_filler(d: &[u8], count_pos: usize, limit: u32) -> Option<V20FillerHit>

Locates the count that follows a v20 filler record, given the offset the bad count was read from. Pure byte logic, exposed for tests. SketchUp 2020 (v20) writes an extra, undocumented record ahead of some counts that v17 does not have, which leaves the reader a few bytes early and makes it read garbage as the count. The filler is an empty UTF-16 string record followed by zero padding:

  <ff fe ff> <u8 0>        empty string
  <zero padding>           runs up to the real count
```rust
Rather than hard-code an offset (the number of bytes before the marker
differs per call site), locate the marker in the short window ahead, then
take the first plausible u32 that follows the padding. Only the EMPTY-
string form counts as filler: a real string here would mean genuine data,
and moving the cursor past it would corrupt the parse.
Returns `None` when the bytes do not match the filler layout.

<a id="cc_skp-legacy-find_empty_root_after_v20_filler"></a>

### fn `find_empty_root_after_v20_filler`

```rust
pub fn find_empty_root_after_v20_filler(d: &[u8], count_pos: usize) -> Option<usize>

The SketchUp 2020 layout of a model with NO component definitions AND no root entities. find_count_after_v20_filler cannot see it: behind the filler (an empty string record, then 13 bytes of padding) the only count is the ROOT entity count, and it is 0, which that search skips as “no count”. Returns the offset of that root count (so the caller can put the cursor there and read the zero), or None when the bytes are not that layout: the empty string record has to sit within 12 bytes of count_pos, and the 13 padding bytes and the count behind it have to be all zero.

fn find_v20_filler_marker

pub(crate) fn find_v20_filler_marker(d: &[u8], count_pos: usize) -> Option<usize>

The empty-string filler marker in the 12 bytes from count_pos, or None (also when the string there is not empty: that is real data).

fn read_legacy_attribute_value

pub fn read_legacy_attribute_value(data: &[u8], pos: usize, type_tag: u8) -> Result<(ParsedAttribute, usize)>

Decodes one typed CAttributeNamed value of type type_tag starting at pos; returns the value and the offset just past it. Exposed for tests.

fn parse_legacy

pub fn parse_legacy(data: &[u8], o: &ParseOptions) -> Result<RawParsed, SkpParseError>

Reads a classic (pre-2021) MFC-archive .skp buffer.

cc_skp::legacy::archive

crates/cc_skp/src/legacy/archive.rs

The MFC object-graph walk (legacy.cpp’s struct Archive, the per-class readers and walk_model).

Items: Value · is_class_ref · Archive · WalkResult · bootstrap_two_materials · probe_layer_anchor_bases · walk_with_bases

type alias Value

pub(crate) type Value = Rc<LegacyValue>

A decoded value (always present for an object read in full).

fn is_class_ref

pub(crate) fn is_class_ref(d: &[u8], p: usize, slot: u64) -> bool

struct Archive

pub(crate) struct Archive<'a>

Fields

Some fields are private.

Methods

struct WalkResult

pub(crate) struct WalkResult<'a>

The finished walk: the archive (its slot table holds every object), the root entity list, and the layers and materials in file order.

Fields

fn bootstrap_two_materials

pub(crate) fn bootstrap_two_materials(data: &[u8], ver: i32, mat_hdr: usize) -> Result<u64>

fn probe_layer_anchor_bases

pub(crate) fn probe_layer_anchor_bases(data: &[u8], ver: i32, start: usize, mat_count: u32) -> Result<Vec<u64>>

fn walk_with_bases

pub(crate) fn walk_with_bases<'a>(data: &'a [u8], ver: i32, start: usize, mat_count: u32, bases: &[u64]) -> Result<WalkResult<'a>>

cc_skp::legacy::pages

crates/cc_skp/src/legacy/pages.rs

Scenes (CViewPage records) in a classic file’s document tail (legacy.cpp’s scan_pages_for_layers and read_page_list).

Items: scan_pages_for_layers · read_page_list

fn scan_pages_for_layers

pub fn scan_pages_for_layers(data: &[u8], start_pos: usize, mut slots: LegacySlotTable) -> Result<Vec<RawPage>>

Best-effort scan for CViewPage (scene) records in a legacy (pre-2021 MFC) file: name + hidden-layer slot ids only, for the narrow capture-flag combinations this reader understands. start_pos is the byte offset to begin scanning from (where the main entity walk stopped, in a real parse). Runs as an independent scan over the file tail rather than a sequential archive read: each candidate is validated by its own local structure (a name string immediately followed by an empty second string and a recognized flags word), and any candidate that doesn’t fully validate is silently skipped, so a page this reader can’t fully understand is just absent instead of wrong. Mirrors Python’s legacy._scan_pages. Errors only where the C++ throws out of the scan (a flags word cut off by the end of the buffer, an unreadable header version).

fn read_page_list

pub(crate) fn read_page_list(data: &[u8], ar: &Archive) -> Option<Vec<RawPage>>

Every scene, with its camera and hidden layers, read as a sequence from the scene list in the file tail. None when there is a scene list this reader can’t fully read; an empty list when there is none.

cc_skp::legacy::reader

crates/cc_skp/src/legacy/reader.rs

The bounds-checked cursor the legacy archive reads through (legacy.cpp’s struct R).

Items: R · decode_utf16le · header_major

struct R

pub(crate) struct R<'a>

A read cursor over the whole file: every read is bounds-checked and fails with out_of_range (“legacy archive truncated”) past the end.

Traits: Debug, Clone, Copy

Fields

Methods

fn decode_utf16le

pub(crate) fn decode_utf16le(units: &[u8]) -> String

UTF-16LE code units to UTF-8. The C++ converts unit by unit (no surrogate pairing); a Rust String must be valid UTF-8, so surrogate pairs are combined and a lone surrogate becomes U+FFFD. BMP text is identical.

fn header_major

pub(crate) fn header_major(data: &[u8]) -> Option<std::result::Result<i32, ()>>

The major version from the {N. in the header’s first 96 bytes (NULs dropped), as the C++ std::regex("\\{(\\d+)\\.") + std::stoi read it: None when there is no such text, Some(Err) when the digits overflow.

cc_skp::model

crates/cc_skp/src/model.rs

The parsed SketchUp model (model.hpp / model.cpp).

Items: EntityId · ByteBuffer · Vec3 · Color3 · Color4 · METRES_TO_INCHES · AttributeKind · ParsedAttribute · format_double · ParsedAttrDict · ParsedAttrDictionaries · StringDictionaries · stringify_attr_dict · stringify_attr_dictionaries · Vertex · Edge · ArcCurve · CoEdge · Face · Layer · Texture · Material · StyleItem · StyleWatermark · Style · Instance · SectionPlane · TextEntity · Dimension · constrained_offset_vector · ConstructionLine · ConstructionPoint · Page · ViewCamera · LooseEdgeRun · Definition · loose_edge_runs · SkpModel

type alias EntityId

pub type EntityId = i64

Unique entity id from the file.

type alias ByteBuffer

pub type ByteBuffer = Vec<u8>

Raw bytes.

type alias Vec3

pub type Vec3 = [f64; 3]

(x, y, z).

type alias Color3

pub type Color3 = [u8; 3]

RGB 0..255.

Traits: MaterialColor

type alias Color4

pub type Color4 = [u8; 4]

RGBA 0..255.

Traits: MaterialColor

const METRES_TO_INCHES

pub const METRES_TO_INCHES: f64

1 metre = 39.37007874015748 inches (SketchUp native unit). Shared by every exporter that takes a coordinate scale factor.

enum AttributeKind

pub enum AttributeKind

The C++ ParsedAttribute::Kind an attribute value maps to. The Rust enum ParsedAttribute distinguishes a few more SketchUp types (Point3d vs Vector3d, Time) that the C++ port folds into Vec / Integer.

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash

Variants

enum ParsedAttribute

pub enum ParsedAttribute

One attribute-dictionary value, covering every value type SketchUp stores (legacy CAttributeNamed types 0/4/6/7/9/10/11/12/17/18 and the VFF A438 wrapper’s AD38/A738/A938/AF38/AA38/B438/B538/AE38 tags):

Traits: Debug, Clone, PartialEq, Default, fmt::Display, PartialEq<str>, PartialEq<&str>, PartialEq<String>, From<&str>, From<String>

Variants

Methods

fn format_double

pub fn format_double(v: f64) -> String

Shortest round-trip text of a double, as C++ std::to_chars(double) writes it: the shortest digits, in fixed or scientific notation, whichever is shorter (fixed on a tie); scientific uses a signed, two-digit-minimum exponent (1e+20, 1e-07).

type alias ParsedAttrDict

pub type ParsedAttrDict = BTreeMap<String, ParsedAttribute>

One named dictionary’s entries.

type alias ParsedAttrDictionaries

pub type ParsedAttrDictionaries = BTreeMap<String, ParsedAttrDict>

Dictionaries keyed by their declared name.

type alias StringDictionaries

pub type StringDictionaries = BTreeMap<String, BTreeMap<String, String>>

A stringified dictionary set (scene / JSON / IFC view).

fn stringify_attr_dict

pub fn stringify_attr_dict(src: &ParsedAttrDict) -> BTreeMap<String, String>

Stringifies every value of one dictionary.

fn stringify_attr_dictionaries

pub fn stringify_attr_dictionaries(src: &ParsedAttrDictionaries) -> StringDictionaries

Stringifies every value of every dictionary.

struct Vertex

pub struct Vertex

3D point in raw SketchUp space (Z-up, inches).

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

struct Edge

pub struct Edge

Straight line segment connecting two vertices.

Traits: Debug, Clone, PartialEq, Default

Fields

struct ArcCurve

pub struct ArcCurve

The analytic arc behind a curve: SketchUp’s own ArcCurve. The arc is the set of points center + cos(t) * x_axis + sin(t) * y_axis for t from start_angle to end_angle. For a circle x_axis and y_axis are perpendicular and both of length ArcCurve::radius; an arc scaled non-uniformly stores an affine image of a circle. Lengths are in inches, in the definition’s local space.

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

Methods

struct CoEdge

pub struct CoEdge

Oriented edge reference within a face loop.

Traits: Debug, Clone, Copy, PartialEq, Eq, Default

Fields

struct Face

pub struct Face

Planar polygon bounded by outer and inner (hole) edge loops.

Traits: Debug, Clone, PartialEq, Default

Fields

struct Layer

pub struct Layer

Organization layer (tag).

Traits: Debug, Clone, PartialEq, Default

Fields

struct Texture

pub struct Texture

Embedded texture image data and metadata.

Traits: Debug, Clone, PartialEq, Default

Fields

Methods

struct Material

pub struct Material

Surface material properties.

Traits: Debug, Clone, PartialEq, Default

Fields

struct StyleItem

pub struct StyleItem

One <sty:item> of a style.xml: the raw <t:variant> of a style setting.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct StyleWatermark

pub struct StyleWatermark

One watermark of a style (style.xml item 5001, a <screenimage>), in file order. The “" separator entry is not included.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct Style

pub struct Style

Bundled rendering style settings.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct Instance

pub struct Instance

Component or group placement within a definition.

Traits: Debug, Clone, PartialEq, Default

Fields

struct SectionPlane

pub struct SectionPlane

Section plane entity.

Traits: Debug, Clone, PartialEq, Default

Fields

struct TextEntity

pub struct TextEntity

Text annotation entity.

Traits: Debug, Clone, PartialEq, Default

Fields

struct Dimension

pub struct Dimension

A linear dimension (SketchUp’s Dimension tool). The legacy reader recovers free endpoints and vertex attachments in the owning entities; unresolved attachments remain unset. See SkpModel::dimensions for the VFF model-level, world-space list.

Traits: Debug, Clone, PartialEq, Default

Fields

fn constrained_offset_vector

pub(crate) fn constrained_offset_vector(axis: u32, normal: Vec3, x: Vec3, offset: f64) -> Option<Vec3>

The offset vector of a dimension constrained to a plane axis (axis 1 or 2), from its plane normal, X axis x and signed offset; None for any other mode, which keeps only the scalar offset.

struct ConstructionLine

pub struct ConstructionLine

A construction/guide line: point + normalized direction; start/end are unset when the line is unbounded in that direction.

Traits: Debug, Clone, PartialEq, Default

Fields

struct ConstructionPoint

pub struct ConstructionPoint

A construction/guide point.

Traits: Debug, Clone, PartialEq, Default

Fields

struct Page

pub struct Page

A saved scene (“page”).

Traits: Debug, Clone, PartialEq, Default

Fields

struct ViewCamera

pub struct ViewCamera

A view camera (VFF 34BC record).

Traits: Debug, Clone, Copy, PartialEq, Default

Fields

struct LooseEdgeRun

pub struct LooseEdgeRun

One ordered run of loose edges (see Definition::loose_edge_runs).

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct Definition

pub struct Definition

Reusable geometry container (component definition or group).

Traits: Debug, Clone, PartialEq, Default

Fields

Methods

fn loose_edge_runs

pub fn loose_edge_runs(definition: &Definition) -> Vec<LooseEdgeRun>

Free-function form of Definition::loose_edge_runs (Python API name).

struct SkpModel

pub struct SkpModel

Top-level model: definitions, layers, materials, styles and scenes.

Traits: Debug, Clone, PartialEq, Default

Fields

Methods

cc_skp::observability

crates/cc_skp/src/observability.rs

Parse progress and log callbacks (observability.hpp).

Items: LogLevel · ParseStage · stage_name · ParseProgress · ProgressFn · LogFn · ParseOptions · PROGRESS_INTERVAL · emit_log · emit_progress

enum LogLevel

pub enum LogLevel

Severity of a log message emitted through ParseOptions::log.

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash

Variants

enum ParseStage

pub enum ParseStage

The stage of the parse pipeline a progress report or error refers to.

Traits: Debug, Clone, Copy, PartialEq, Eq, Hash, fmt::Display

Variants

Methods

fn stage_name

pub const fn stage_name(s: ParseStage) -> &'static str

The stage’s snake_case name ("header", "zip_extract", …).

struct ParseProgress

pub struct ParseProgress

One progress report: current of total units done in stage.

Traits: Debug, Clone, Copy, PartialEq, Eq

Fields

type alias ProgressFn

pub type ProgressFn = dyn Fn(&ParseProgress) + Send + Sync

Progress callback type.

type alias LogFn

pub type LogFn = dyn Fn(LogLevel, &str) + Send + Sync

Log callback type.

struct ParseOptions

pub struct ParseOptions

Optional progress and logging callbacks. Both are invoked synchronously on the calling thread.

Traits: Clone, Default, fmt::Debug

Fields

Methods

const PROGRESS_INTERVAL

pub const PROGRESS_INTERVAL: u64

Progress is reported every this many records (and on the last one).

fn emit_log

pub fn emit_log(o: &ParseOptions, level: LogLevel, message: &str)

Invokes the log callback, if any (emit_log).

fn emit_progress

pub fn emit_progress(o: &ParseOptions, stage: ParseStage, current: u64, total: u64)

Invokes the progress callback, if any (emit_progress).

cc_skp::parser

crates/cc_skp/src/parser.rs

Public entry points (parser.hpp / parser.cpp).

Items: parse_skp · build_scene · build_instanced_scene · SkpFile

fn parse_skp

pub fn parse_skp(buffer: &[u8], options: &ParseOptions) -> Result<SkpModel, SkpParseError>

Parses an SKP buffer into its definitions, geometry, materials, layers, and styles. Callbacks in options run synchronously on this thread.

fn build_scene

pub fn build_scene(buffer: &[u8], options: &ParseOptions) -> Result<Scene, SkpParseError>

Parses an SKP buffer and bakes it into world-space, GLB-ready scene data.

fn build_instanced_scene

pub fn build_instanced_scene(buffer: &[u8], options: &ParseOptions) -> Result<InstancedScene, SkpParseError>

Parses an SKP buffer and builds the placed scene graph with SketchUp’s component/group instancing PRESERVED instead of baked into world-space vertex data: output grows with unique geometry + instance transforms rather than definition geometry x placement count.

struct SkpFile

pub struct SkpFile

In-memory handle for repeatedly parsing or baking one SKP source. Each call starts from the original bytes and performs an independent parse.

Traits: Debug, Clone, PartialEq, Eq

Some fields are private.

Methods

cc_skp::scene

crates/cc_skp/src/scene.rs

The baked, world-space scene (scene.hpp). Types only; the builder lives in scene_build.rs.

Items: InstanceNode · MeshMetadata · GlbPrimitive · PbrMetallicRoughness · GltfMaterial · SceneTexture · CurveArc · CurveSetMetadata · Scene

struct InstanceNode

pub struct InstanceNode

One node of the baked instance tree.

Traits: Debug, Clone, PartialEq, Default

Fields

struct MeshMetadata

pub struct MeshMetadata

Metadata for one baked mesh, keyed like its primitive’s geom_name.

Traits: Debug, Clone, PartialEq, Default

Fields

struct GlbPrimitive

pub struct GlbPrimitive

One triangulated, world-space mesh (metres, glTF Y-up).

Traits: Debug, Clone, PartialEq, Default

Fields

struct PbrMetallicRoughness

pub struct PbrMetallicRoughness

glTF pbrMetallicRoughness.

Traits: Debug, Clone, PartialEq, Default

Fields

struct GltfMaterial

pub struct GltfMaterial

One glTF material.

Traits: Debug, Clone, PartialEq, Default

Fields

struct SceneTexture

pub struct SceneTexture

One texture image referenced by the scene’s glTF materials.

Traits: Debug, Clone, PartialEq, Eq, Default

Fields

struct CurveArc

pub struct CurveArc

An analytic arc recovered for a loose-edge run (Python port extension): points in the run’s own frame plus 0-based (start, mid, end) index triples into them, ready to become IFC4 IfcArcIndex entries.

Traits: Debug, Clone, PartialEq, Default

Fields

struct CurveSetMetadata

pub struct CurveSetMetadata

Metadata for one run of loose edges - edges no face uses (Python port extension; the C++ port does not emit these). Points are world-space metres in glTF’s Y-up frame, like GlbPrimitive::positions.

Traits: Debug, Clone, PartialEq, Default

Fields

struct Scene

pub struct Scene

The result of build_scene(): the placed instances baked into a flat, world-space scene.

Traits: Debug, Clone, PartialEq, Default

Fields

cc_skp::scene_build

crates/cc_skp/src/scene_build.rs

The baked scene builder (scene.cpp’s build_scene_raw), plus the Python port’s loose-edge curve sets (scene.py’s curve_sets).

Items: IDENTITY · is_generic_definition_name · omitted_from_scene · name_override · scene_dictionaries · instance_layer · definition_name · curve_fallback_layer · run_layer · build_error · MAX_COMPONENT_DEPTH · MAX_EXPANDED_INSTANCES · validate_hierarchy · recursive_definition · max_depth_exceeded · max_instances_exceeded · build_scene_raw

const IDENTITY

pub(crate) const IDENTITY: [f64; 13]

The 13-value identity matrix.

fn is_generic_definition_name

pub(crate) fn is_generic_definition_name(name: &str) -> bool

SketchUp’s own auto-generated placeholder definition names (^(?:Group|Component)\d*#\d+$: “Group#1”, “Component#12”, “Group86#2”), which carry no more meaning than the internal index.

fn omitted_from_scene

pub(crate) fn omitted_from_scene(dict_name: &str) -> bool

Scene nodes omit SketchUp’s own dictionaries: dynamic_attributes is already on properties, SU_InstanceSet is Owner/Status boilerplate.

fn name_override

pub(crate) fn name_override(i: &RawInstance) -> Option<String>

The attribute-dictionary display-name override: “name”, “label” or “code” on any dictionary except the omitted ones; first dictionary and first key with a non-empty value wins.

fn scene_dictionaries

pub(crate) fn scene_dictionaries(i: &RawInstance) -> StringDictionaries

The instance’s dictionaries minus the omitted ones, stringified.

fn instance_layer

pub(crate) fn instance_layer(p: &RawParsed, o: &ParseOptions, i: &RawInstance, parent_layer: &str) -> String

An instance’s layer: its own id resolved to a name, the parent’s layer when the id names no layer, or the raw text when it is not a number.

fn definition_name

pub(crate) fn definition_name(p: &RawParsed, i: &RawInstance) -> String

The definition’s name, or "" when the instance names none / an unknown one.

fn curve_fallback_layer

pub(crate) fn curve_fallback_layer(p: &RawParsed, b: &GeometryBuilder, layer: &str) -> String

The fallback layer a definition’s loose edges resolve to (Python port): its own faces’ majority layer when they carry one, else layer.

fn run_layer

pub(crate) fn run_layer(p: &RawParsed, b: &GeometryBuilder, edge_ids: &[EntityId], fallback: &str) -> String

A run’s own layer: its edges’ majority layer, else fallback.

fn build_error

pub(crate) fn build_error(e: Error) -> SkpParseError

A missing vertex (the C++ std::out_of_range from map::at).

const MAX_COMPONENT_DEPTH

pub(crate) const MAX_COMPONENT_DEPTH: usize

Maximum component nesting depth before rejecting the hierarchy.

const MAX_EXPANDED_INSTANCES

pub(crate) const MAX_EXPANDED_INSTANCES: u64

Maximum total expanded component instances in a scene build (guards against exponential DAG expansion / “billion laughs” component graphs).

fn validate_hierarchy

pub(crate) fn validate_hierarchy(p: &RawParsed) -> Result<(), SkpParseError>

Validates component hierarchy depth, cycles, and expanded instance bounds before initiating expensive scene allocation. Uses memoization so DAGs with exponential expansions are detected in linear time O(V + E) without allocating.

fn recursive_definition

pub(crate) fn recursive_definition(id: EntityId) -> SkpParseError

fn max_depth_exceeded

pub(crate) fn max_depth_exceeded(id: EntityId) -> SkpParseError

fn max_instances_exceeded

pub(crate) fn max_instances_exceeded(id: EntityId) -> SkpParseError

fn build_scene_raw

pub fn build_scene_raw(mut p: RawParsed, o: &ParseOptions) -> Result<Scene, SkpParseError>

Bakes a reader’s raw output into a world-space Scene.

cc_skp::triangulator

crates/cc_skp/src/triangulator.rs

Face normals and planar-face triangulation (triangulator.hpp / triangulator.cpp).

Items: compute_face_normal · triangulate_face_3d · triangulate_with

fn compute_face_normal

pub fn compute_face_normal(points: &[Vec3]) -> Option<Vec3>

Newell’s-method unit normal of a polygon, or None for fewer than three points or a degenerate (zero-area) polygon.

fn triangulate_face_3d

pub fn triangulate_face_3d(vertices: &BTreeMap<EntityId, Vertex>, loops: &[Vec<EntityId>], normal: Vec3) -> Vec<[EntityId; 3]>

Triangulates a planar face given as vertex-id loops (loops[0] the outer boundary, the rest holes) in the plane of normal. Returns vertex-id triples; empty when a general-path loop references a vertex missing from vertices.

fn triangulate_with

pub(crate) fn triangulate_with(lookup: impl Fn(EntityId) -> Option<Vec3>, loops: &[Vec<EntityId>], mut n: Vec3) -> Vec<[EntityId; 3]>

triangulate_face_3d over any vertex lookup (the scene builders read the builder’s own id -> position map instead of copying it into Vertexes).

cc_skp::zip

crates/cc_skp/src/zip.rs

Minimal in-memory ZIP reader replacing the miniz mz_zip_reader_* calls core.cpp makes: init from memory, file count/stat, locate by name, and extract to memory (stored or deflated, CRC-checked). The central-directory validation, the case-insensitive heap-sorted name index used by locate, and the extraction checks mirror miniz so the same archives are accepted and rejected.

Items: ZipError · crc32_update · crc32 · ZipFileStat · ZipArchive

enum ZipError

pub enum ZipError

Why an archive or entry was rejected (miniz’s mz_zip_error).

Traits: Debug, Clone, Copy, PartialEq, Eq, fmt::Display, std::error::Error

Variants

fn crc32_update

pub fn crc32_update(crc: u32, data: &[u8]) -> u32

Continues a CRC-32 (IEEE) from crc (0 to start).

fn crc32

pub fn crc32(data: &[u8]) -> u32

CRC-32 (IEEE) of data.

struct ZipFileStat

pub struct ZipFileStat

One entry’s central-directory metadata (mz_zip_archive_file_stat).

Traits: Debug, Clone, PartialEq, Eq

Fields

Methods

struct ZipArchive

pub struct ZipArchive<'a>

A ZIP archive held in memory (mz_zip_reader_init_mem).

Some fields are private.

Methods