API Reference¶
This reference is generated from ldraw.__all__ at build time, then rendered
from the exported objects' type annotations and docstrings with mkdocstrings.
Generated ldraw.library.* modules are intentionally not included because they
depend on the locally downloaded LDraw release. Run ldraw generate and
ldraw stubs in consuming projects for release-specific import and type-stub
coverage.
AnnularProfile
dataclass
¶
Axisymmetric tyre bead or wheel-rim seat.
scaled
¶
Return this profile under radial and axial scaling.
BomRow
dataclass
¶
One line of a bill of materials.
to_dict
¶
Return the row as a plain dict keyed by BOM_FIELDS.
BoundingBox
dataclass
¶
An axis-aligned box in LDraw units (LDU).
LDraw's Y axis points down, so min.y is the highest point of the
part (typically the stud tops) and max.y the lowest.
BoundsGap
dataclass
¶
CameraState
dataclass
¶
Renderer-neutral LPub3D assembly camera state.
merged
¶
Return this state with non-None fields from override applied.
CancellationToken
¶
Thread-safe cancellation token shared by library operations.
CatalogBuildOutcome
¶
CatalogBuildReport
dataclass
¶
Index work and persistence performed by prepare_catalog.
CatalogEntry
dataclass
¶
CatalogPreparationResult
dataclass
¶
Parts plus before/after state and diagnostics from one preparation.
Colour
dataclass
¶
A colour, identified by a code, or by rgb/alpha for direct colours.
rgb is canonicalized on construction to #RRGGBB — a leading
#, six uppercase hex digits — whatever form it was given in;
malformed values raise ValueError.
is_solid
property
¶
Whether this colour is plain opaque paint — no alpha, no finish.
Judged from the data on this instance: full alpha (or none given)
and no colour attributes (CHROME, GLITTER, LUMINANCE,
…). Colours from a parts catalog carry both fields; a bare
Colour(code=...) placeholder carries neither and so reads as
solid — look the code up in Parts.colours_by_code to judge the
real palette entry.
swatch_rgb
property
¶
RGB hex value suitable for colour swatches, when known.
ConnectionContact
dataclass
¶
Two placed connection features that are aligned and overlapping.
ConnectionFeature
dataclass
¶
One physical connection interface in a part's local coordinates.
The feature frame uses local +Y as its axis. The X and Z axes retain cross-section roll, which is significant for Technic axles and clips.
ConnectionGraphEdge
dataclass
¶
One typed feature contact between two occurrence nodes.
ConnectionGraphs
dataclass
¶
ConnectionMetadataCoverage
¶
ConnectionMetadataReport
dataclass
¶
Immutable report for all connection metadata applied to one part.
ConnectionMultigraph
dataclass
¶
ConnectionProvenance
dataclass
¶
Structured origin of a normalized connection feature.
ConnectionResidual
dataclass
¶
Geometric residuals between two compatible features.
ConnectionRole
¶
ConnectionStatus
¶
CylindricalProfile
dataclass
¶
CylindricalSection
dataclass
¶
One axial section of a pin, hole, axle, bar, or clip profile.
scaled
¶
Return this section under radial and axial scaling.
Diagnostic
dataclass
¶
One structured problem, warning, or recovery made by an operation.
line_number remains the first field so the historical
ValidationIssue(line_number, message, severity) constructor stays
source compatible. New callers should prefer keyword arguments.
Warning: equality and hashing deliberately compare only
line_number, message, and severity (historical
ValidationIssue behavior), so set/dict deduplication
collapses diagnostics that differ only by code, path, or
section. To deduplicate diagnostics across files, key on a tuple
such as (diagnostic.path, diagnostic.code, diagnostic.line_number,
diagnostic.message) instead.
code
class-attribute
instance-attribute
¶
section
class-attribute
instance-attribute
¶
offending_value
class-attribute
instance-attribute
¶
suggestions
class-attribute
instance-attribute
¶
cause
class-attribute
instance-attribute
¶
to_dict
¶
Return a JSON-ready representation, including safe cause details.
offending_value passes JSON-native scalars through unchanged;
any other value (bytes, matrices, exceptions, ...) is coerced with
repr() so the result always survives json.dumps.
DiagnosticCode
¶
Bases: StrEnum
Stable codes emitted by PyLDraw report-oriented operations.
CATALOG_LIBRARY_MISSING
class-attribute
instance-attribute
¶
CATALOG_INDEX_MISSING
class-attribute
instance-attribute
¶
CATALOG_INDEX_STALE
class-attribute
instance-attribute
¶
CATALOG_INDEX_UNREADABLE
class-attribute
instance-attribute
¶
CATALOG_PERSIST_FAILED
class-attribute
instance-attribute
¶
PARSE_INVALID_NUMERIC
class-attribute
instance-attribute
¶
PARSE_INVALID_COLOUR
class-attribute
instance-attribute
¶
MPD_MISPLACED_NOFILE
class-attribute
instance-attribute
¶
MPD_CONTENT_AFTER_NOFILE
class-attribute
instance-attribute
¶
MPD_DUPLICATE_SECTION
class-attribute
instance-attribute
¶
MPD_UNRESOLVED_SUBMODEL
class-attribute
instance-attribute
¶
MODEL_UNKNOWN_COLOUR
class-attribute
instance-attribute
¶
MODEL_LEGACY_COLOUR
class-attribute
instance-attribute
¶
MODEL_SINGULAR_MATRIX
class-attribute
instance-attribute
¶
MODEL_NON_ORTHONORMAL_MATRIX
class-attribute
instance-attribute
¶
PART_HEADER_INVALID
class-attribute
instance-attribute
¶
PART_REFERENCE_UNRESOLVED
class-attribute
instance-attribute
¶
PART_REFERENCE_CYCLE
class-attribute
instance-attribute
¶
GEOMETRY_INCOMPLETE
class-attribute
instance-attribute
¶
CONNECTION_UNSUPPORTED_RECORD
class-attribute
instance-attribute
¶
CONNECTION_UNSUPPORTED_OPTION
class-attribute
instance-attribute
¶
CONNECTION_INVALID_OPTION_VALUE
class-attribute
instance-attribute
¶
CONNECTION_METADATA_INVALID
class-attribute
instance-attribute
¶
CONNECTION_MISSING_REQUIRED_OPTION
class-attribute
instance-attribute
¶
CONNECTION_INCLUDE_NOT_FOUND
class-attribute
instance-attribute
¶
CONNECTION_INCLUDE_CYCLE
class-attribute
instance-attribute
¶
CONNECTION_FEATURE_CONFLICT
class-attribute
instance-attribute
¶
CONNECTION_INVALID_TRANSFORM
class-attribute
instance-attribute
¶
CONNECTION_INVALID_GRID
class-attribute
instance-attribute
¶
DISCOVERY_INVALID_LIBRARY
class-attribute
instance-attribute
¶
DOWNLOAD_PLAN_FAILED
class-attribute
instance-attribute
¶
DOWNLOAD_INTEGRITY_FAILED
class-attribute
instance-attribute
¶
DownloadPlan
dataclass
¶
Network and local-cache facts for a prospective library download.
remaining_bytes
property
¶
Return the expected remaining transfer size when known.
FingerProfile
dataclass
¶
Interlocking hinge fingers arranged along the hinge axis.
scaled
¶
Return this profile under radial and axial scaling.
GenericBounds
dataclass
¶
GenericMatch
¶
GenericPlacement
¶
GenericProfile
dataclass
¶
InstructionBuilder
¶
Write balanced instruction directives into a Model.
rotation_step
¶
rotation_step(
x: float,
y: float,
z: float,
*,
mode: RotationMode = RotationMode.RELATIVE,
) -> None
Append a rotation-step boundary.
arrow
¶
Append a section-local 3D arrow annotation.
highlight
¶
Highlight an existing placement using proximity-safe metadata.
page_break
¶
Append an LPub3D page break.
set_camera
¶
set_camera(
camera: CameraState,
*,
scope: InstructionScope = InstructionScope.LOCAL,
context: CameraContext = CameraContext.ASSEMBLY,
) -> None
Append canonical LPub3D camera directives for non-None fields.
callout
¶
Write a balanced LPub3D callout range.
ignore
¶
Write a balanced LPub3D inventory-ignore range.
InstructionDocument
dataclass
¶
InstructionIssue
dataclass
¶
A structural or semantic instruction problem.
InstructionSection
dataclass
¶
The independent instruction sequence for one model section.
InstructionStep
dataclass
¶
One section-local building step and its effective instruction state.
cumulative_pieces
property
¶
Direct placements accumulated in this section through this step.
cumulative_objects
property
¶
Parsed objects accumulated in this section through this step.
source_line_for
¶
Return the source line for one object in this step's section.
added_occurrences
¶
Return leaf occurrences added in this step.
cumulative_occurrences
¶
Return leaf occurrences accumulated through this step.
added_bill_of_materials
¶
added_bill_of_materials(
*,
parts: Parts | None = None,
expand_submodels: bool = True,
respect_lpub: bool = True,
) -> list[BomRow]
Return the parts tray for placements added in this step.
cumulative_bill_of_materials
¶
cumulative_bill_of_materials(
*,
parts: Parts | None = None,
expand_submodels: bool = True,
respect_lpub: bool = True,
) -> list[BomRow]
Return the accumulated BOM through this step.
LDCadShadowLibrary
¶
Read unpacked, ZIP, or CSL LDCad shadow metadata.
connections_for
¶
connections_for(
code: str,
*,
siblings: tuple[LDCadShadowLibrary, ...] = (),
) -> ShadowConnectionResult
Return resolved shadow features for a part or primitive code.
siblings is the full ordered registry of shadow libraries used to
resolve SNAP_INCL references across the merged shadow namespace.
LDrawCapability
¶
LDrawPaths
dataclass
¶
Resolved filesystem paths for one pyldraw configuration.
LDrawSession
¶
Manage one configured LDraw catalog and generated library.
state
¶
state(
*,
capabilities: Iterable[LDrawCapability] | None = None,
fingerprint: CatalogFingerprint | None = None,
) -> LDrawState
Classify only the configured capabilities requested by the caller.
capabilities=None (the default) means every capability; an
empty iterable raises ValueError, matching prepare_catalog.
prepare_catalog
¶
prepare_catalog(
*,
capabilities: Iterable[LDrawCapability] = (
LDrawCapability.CATALOG,
),
connection_shadows: Iterable[str | Path] = (),
studio_metadata: Iterable[str | Path] = (),
force: bool = False,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
fingerprint: CatalogFingerprint | None = None,
) -> CatalogPreparationResult
Load or rebuild requested data using one filesystem fingerprint.
fingerprint lets a caller reuse an already-computed snapshot to
avoid a second parts-tree walk; the caller is then responsible for
its freshness — a stale value persists the index under stale keys.
rebuild_index
¶
rebuild_index(
*,
force: bool = True,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
fingerprint: CatalogFingerprint | None = None,
) -> Parts
Rebuild the persistent catalog index and return the loaded parts.
fingerprint lets a caller reuse an already-computed snapshot;
the caller is then responsible for its freshness — the rebuilt
index is persisted under exactly the keys it carries, so a stale
value poisons the index until the next filesystem change.
load_model
¶
load_model(
path: Path | str,
parts: Parts | None = None,
*,
tolerant: bool = True,
) -> ModelLoadResult
Read and validate a model into a structured load result.
LDrawState
dataclass
¶
Freshness state for a configured LDraw library and generated data.
capabilities
class-attribute
instance-attribute
¶
capabilities: frozenset[LDrawCapability] = frozenset(
{
LDrawCapability.CATALOG,
LDrawCapability.GENERATED_MODULES,
}
)
ready
property
¶
Whether every capability this state was scoped to is fresh.
Only the capabilities in :attr:capabilities were classified;
unrequested capabilities may still be missing or stale.
library_available
property
¶
Whether parts.lst exists and catalog loading can start.
needs_index_rebuild
property
¶
Whether loading will need the slow catalog categorization pass.
needs_generation
property
¶
Whether ldraw.library should be generated or refreshed.
LDrawStateReason
¶
LibraryComponent
dataclass
¶
LibraryInspection
dataclass
¶
LibraryOrigin
¶
Matrix
dataclass
¶
A 3x3 transformation matrix.
Model
dataclass
¶
A whole LDraw model, optionally with MPD submodels.
Models compare and hash by identity: their objects contain
identity-compared pieces, so field-wise equality would be meaningless.
Compare model content with m1.to_ldraw() == m2.to_ldraw().
objects
class-attribute
instance-attribute
¶
submodels
class-attribute
instance-attribute
¶
description
property
¶
The description from the first line, when it is an unmanaged comment.
steps
property
¶
Pieces grouped by 0 STEP markers.
Pieces after the last marker form a final step, so a model without
any 0 STEP lines is a single step. A trailing marker does not
produce an empty step. Submodel references are not expanded.
submodel_for
¶
Resolve a piece's subfile reference to a submodel, if any.
source_line_for
¶
Return the parsed source line for this exact object.
add
¶
Append parsed objects (pieces, comments, geometry) to the model.
add_group
¶
Append a group's pieces; group transforms apply at serialization.
from_pieces
classmethod
¶
from_pieces(
pieces: Iterable[Piece],
*,
name: str = "",
description: str | None = None,
author: str | None = None,
) -> Self
Build a model from pieces, optionally with header comments.
set_header
¶
set_header(
*,
description: str | None = None,
name: str | None = None,
author: str | None = None,
ldraw_org: str | None = None,
license: str | None = None,
) -> None
Set or replace standard header lines at the top of the model.
ldraw_org and license write the 0 !LDRAW_ORG and
0 !LICENSE meta commands, placed after any Name:/Author:
comments in canonical header order.
add_submodel
¶
add_submodel(
submodel: Model,
*,
colour: Colour | int = MAIN_COLOUR_CODE,
position: Vector | None = None,
matrix: Matrix | None = None,
) -> Piece
Register a submodel and append a type-1 piece referencing it.
The submodel's own nested submodels are hoisted into this model's
flat mapping, since serialization only walks one level. The same
submodel object may be added repeatedly; each call appends another
placement piece. A different model under an already-registered
name still raises DuplicateSubmodelError.
submodel_view
¶
Return a submodel that resolves references against this root.
Models taken straight from Model.submodels have an empty
submodel table, so iterating them treats references to sibling
submodels as leaf pieces. The returned model shares this root's
submodel table instead, making iter_pieces,
bill_of_materials, and find_pieces(recursive=True) expand
nested references correctly. It is a live view — its objects and
submodel table are shared with this model, not copied.
Raises UnknownSubmodelError for a name that is neither this
model's nor one of its submodels'.
add_rotation_step
¶
Append a canonical MLCad ROTSTEP instruction boundary.
end_rotation_steps
¶
Append 0 ROTSTEP END and restore the default instruction view.
instruction_document
¶
Interpret this model and its reachable submodels as instructions.
iter_instruction_steps
¶
Yield this model section's semantic instruction steps.
This convenience method constructs the complete instruction document,
including reachable and orphan sections. Callers that need to inspect
steps repeatedly should build :meth:instruction_document once and
reuse its root.steps tuple.
iter_pieces
¶
Recursively yield leaf pieces, expanding submodel references.
References are resolved against this model's submodel table. A
model taken straight from Model.submodels has an empty table,
so references to sibling submodels are silently yielded as if they
were leaf pieces — inspect a submodel through
root.submodel_view(name) instead.
iter_occurrences
¶
iter_occurrences(
*,
expand_submodels: bool = True,
include_steps: bool = True,
) -> Iterator[ModelOccurrence]
Yield placed part occurrences with transform and source context.
bill_of_materials
¶
Count leaf pieces by part and colour, expanding submodel references.
Colour 16 (the main colour) inside a submodel is resolved to the
colour the submodel was placed with. As with iter_pieces,
submodel references only resolve against this model's own submodel
table; to count a single submodel of a larger model, call this on
root.submodel_view(name). Cyclic submodel references (possible
in tolerantly-loaded models) are skipped instead of raising.
find_pieces
¶
find_pieces(
*,
part: str | None = None,
colour: Colour | int | None = None,
recursive: bool = False,
) -> list[Piece]
Return pieces matching the given part code and/or colour.
Part codes are compared case-insensitively.
ModelAnalysis
dataclass
¶
Occurrences, statistics, BOM, steps, and diagnostics for one model.
ModelInspection
dataclass
¶
Exact bounds, resolved occurrences, failures, and source attribution.
stud_contacts
¶
Return strict stud matches as the historical stud-contact view.
connection_contacts
¶
connection_contacts(
*,
tolerance: float = 0.25,
angular_tolerance: float = 2.0,
) -> tuple[ConnectionContact, ...]
Return compatible connection features already mated in the model.
connection_graphs
¶
connection_graphs(
*,
tolerance: float = 0.25,
angular_tolerance: float = 2.0,
) -> ConnectionGraphs
Return confirmed and heuristic-inclusive occurrence multigraphs.
snap_candidates
¶
snap_candidates(
moving: OccurrenceGeometry | int,
*,
fixed: OccurrenceGeometry | int | None = None,
limit: int | None = None,
) -> tuple[SnapCandidate, ...]
Return ranked placements for mating a moving occurrence's features.
moving and fixed accept either an occurrence geometry or its
stable inspection index. When fixed is omitted, every other
occurrence is considered.
contact_gaps
¶
contact_gaps(
*, minimum_gap: float = 5.0, chronological: bool = False
) -> tuple[OccurrenceContact, ...]
Return occurrences farther than minimum_gap from every peer.
ModelLoadResult
dataclass
¶
Model, diagnostics, and source completeness from one read/parse pass.
analyze
¶
Analyze the loaded model without discarding its diagnostics.
ModelOccurrence
dataclass
¶
One placed leaf part occurrence in a model.
Occurrences are traversal events: two placements of the same submodel produce distinct occurrences, so they compare and hash by identity.
step is the effective (inherited) step: pieces inside a submodel
report the step their outermost placement belongs to. This differs
from path[-1].step, which is the placement's local step within
its own section (OccurrencePathItem.local_step); source_step
carries the same local semantics.
ModelSummary
dataclass
¶
Reusable summary of a model's placed parts and geometry extents.
from_model
classmethod
¶
Build a summary for model using geometry from parts.
Cyclic submodel references (possible in tolerantly-loaded models) are skipped rather than raising.
from_inspection
classmethod
¶
Build a summary reusing bounds already computed by an inspection.
inspect_model already transforms every occurrence's expanded
points into exact world bounds; this constructor folds those
results instead of recomputing them, so callers building both an
inspection and a summary pay for the geometry only once.
from_occurrences
classmethod
¶
Build a summary from occurrences already traversed by a caller.
OccurrenceAttribution
dataclass
¶
OccurrenceContact
dataclass
¶
OccurrenceGeometry
dataclass
¶
Expanded local geometry transformed into one occurrence's world frame.
occurrence
property
¶
Return the source occurrence represented by this geometry.
OccurrencePathItem
dataclass
¶
One local placement in a root-to-leaf occurrence path.
step
property
¶
Compatibility spelling for local_step — the local step.
This is the step counted within the placement's own section, not
the inherited one, so for submodel contents it differs from
ModelOccurrence.step (which is the effective step). Use
effective_step for the inherited semantics.
OperationCancelled
¶
Bases: Exception
A caller requested cancellation of an in-progress operation.
Deliberately derives from Exception rather than RuntimeError:
setup helpers such as ensure_library wrap genuine failures in
RuntimeError, so a caller's except RuntimeError must not
misreport a user-requested cancel as a failure.
PartCategory
¶
Bases: StrEnum
Known LDraw part categories, mirroring the official LDraw.org list.
CONSTRACTION_ACCESSORY
class-attribute
instance-attribute
¶
module_name
property
¶
Return the generated module name for this category.
These names are a frozen public contract: renaming one would break
existing ldraw.library.parts.* imports.
from_label
classmethod
¶
Return the category matching an LDraw label.
PartCompatibility
dataclass
¶
PartGeometry
dataclass
¶
PartHistoryEntry
dataclass
¶
PartInspection
dataclass
¶
Part lookup, metadata, references, geometry, and explicit failures.
PartMetadata
dataclass
¶
PartReference
dataclass
¶
A type-1 subfile reference found inside a part file.
Parts
¶
Part catalog loader.
ColourAttributes
class-attribute
instance-attribute
¶
ColourAttributes = (
"CHROME",
"PEARLESCENT",
"RUBBER",
"MATTE_METALLIC",
"METAL",
"GLITTER",
"SPECKLE",
"LUMINANCE",
)
by_category
instance-attribute
¶
library_root
property
¶
Directory containing parts.lst, parts, primitives, and colours.
tyre_rim_compatibility
property
¶
Tyre/rim pairs evidenced by official complete-part shortcuts.
get
classmethod
¶
get(
parts_lst: str | Path,
*,
tree_fingerprint: str | None = None,
parts_lst_md5: str | None = None,
connection_shadows: Iterable[str | Path] = (),
studio_metadata: Iterable[str | Path] = (),
) -> Parts
Get a memoized Parts keyed by list and optional content fingerprints.
Omitting parts_lst_md5 memoizes under a different key than
passing it, so mixing both styles for one file parses it twice.
Directory connection sources are deliberately not walked on cache
lookup; call fresh after editing their nested contents.
clear_cache
classmethod
¶
Clear memoized instances, including stale directory sources.
fresh
classmethod
¶
fresh(
parts_lst: str | Path,
*,
tree_fingerprint: str | None = None,
parts_lst_md5: str | None = None,
connection_shadows: Iterable[str | Path] = (),
studio_metadata: Iterable[str | Path] = (),
) -> Parts
Return a freshly constructed Parts, replacing the memoized one.
Explicit rebuild paths call this to guarantee a genuinely fresh categorization and reload nested connection-source edits; the memo is repopulated with the fresh instance.
from_catalog
classmethod
¶
Construct a Parts that adopts a prebuilt catalog.
Skips the expensive per-part categorization pass.
adopt_catalog
¶
Adopt a prebuilt catalog, skipping categorization.
A no-op when this instance is already categorized, so a memoized instance can safely adopt the same persisted index repeatedly.
build_catalog
¶
build_catalog(
*,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
) -> PartsCatalog
Materialize the catalog with determinate progress and cancellation.
get_entry_by_code
¶
Return a typed catalog entry by part code.
get_entry_by_description
¶
Return a typed catalog entry by part description.
entries_by_category
¶
Return entries in a part category.
minifig_entries
¶
Return entries in minifigure sections.
get_category
¶
Get the category of a part based on its description.
load
¶
Load the parts list, colours, and primitives (all cheap passes).
The expensive categorization pass — opening every part file for its
!CATEGORY header — runs lazily on first catalog access.
section_find
¶
Return code and description from a parts.lst split line.
The description is kept exactly as written in parts.lst;
detected minifig sections are recorded for the catalog. Generated
symbol names strip the Minifig prefix at generation time
(see symbol_description).
description_for
¶
Return the parts.lst description for a part code, or None.
The lookup tolerates casing differences: Piece.part preserves
whatever casing the source used while parts.lst codes are
typically lowercase, so the code is tried as given, lowercased,
and uppercased.
part
¶
Get a Part from its description or code.
Raises PartNotFoundError when the description or code is not
in the library or the part file is missing; use find_part for
a lookup that returns None instead.
find_part
¶
Get a Part from its description or code, or None when not found.
bounding_box
¶
Axis-aligned bounding box of a part's geometry, in LDU.
Subfiles are resolved recursively; unresolvable ones are skipped
with a warning. Raises PartNotFoundError for an unknown code
and NoGeometryError when the part draws nothing.
geometry
¶
Return exact expanded geometry and completeness diagnostics.
connections
¶
Return physical connection features detected for a part.
connection_metadata
¶
Return features and normalized metadata coverage for a part.
add_connection_shadow
¶
Add an LDCad shadow library as an optional connection source.
Sources are applied in registration order; later sources can clear or supersede features from earlier sources.
clear_connection_shadows
¶
Remove all configured LDCad shadow-library sources.
add_studio_metadata
¶
Add a Studio connectivity JSON source at Studio precedence.
clear_studio_metadata
¶
Remove every configured Studio connectivity source.
set_connection_overrides
¶
set_connection_overrides(
code: str,
features: Iterable[ConnectionFeature],
*,
replace_existing: bool = False,
) -> None
Register authoritative connection features for one part.
By default overrides augment inferred and shadow-derived features.
Set replace_existing to discard every lower-priority feature.
clear_connection_overrides
¶
Remove connection overrides for one part or the whole library.
compatible_tyres
¶
Return tyre codes evidenced as compatible with rim_code.
compatible_rims
¶
Return rim codes evidenced as compatible with tyre_code.
inspect_part
¶
inspect_part(
code: str,
*,
include_geometry: bool = True,
recursive_references: bool = False,
) -> PartInspection
Inspect one part without translating failures into empty data.
studs
¶
All stud primitives a part places, in the part's own coordinates.
Includes underside tubes and other downward studs; filter with
StudReference.is_top_stud or use stud_positions.
stud_positions
¶
Positions of a part's top studs (upward connectors), in LDU.
resolve_colour
¶
Return catalog metadata for colour when it is known.
references_for
¶
Return type-1 references placed by a part file.
PartsCatalog
dataclass
¶
Typed collection of part catalog entries.
by_code
class-attribute
instance-attribute
¶
by_description
class-attribute
instance-attribute
¶
by_category
class-attribute
instance-attribute
¶
by_category: defaultdict[
PartCategory, list[CatalogEntry]
] = field(default_factory=lambda: defaultdict(list))
by_minifig_section
class-attribute
instance-attribute
¶
by_minifig_section: defaultdict[
MinifigSection, list[CatalogEntry]
] = field(default_factory=lambda: defaultdict(list))
get_entry_by_code
¶
Return a catalog entry by part code.
get_entry_by_description
¶
Return a catalog entry by part description.
entries_by_category
¶
Return catalog entries in a category.
minifig_entries
¶
Return minifigure catalog entries, optionally for one section.
search
¶
search(
query: str,
*,
within: Iterable[CatalogEntry] | None = None,
fields: Iterable[
CatalogSearchField
] = ALL_CATALOG_SEARCH_FIELDS,
limit: int | None = None,
) -> tuple[CatalogEntry, ...]
Return normalized token matches in deterministic relevance order.
Every token must occur somewhere in the selected fields. within
scopes the search to a caller-provided category or other subset.
module_sections
¶
Return generated module sections keyed by package path.
Section dicts are keyed by the catalog description exactly as
written in parts.lst; symbol names (including minifig-prefix
stripping) are derived at generation time, where collisions are
deduplicated with part-code suffixes.
Person
¶
Representation of a LEGO minifigure.
hat
¶
Add a hat piece to the figure's head.
backpack
¶
Add a backpack.
hips_and_legs
¶
Add combined hips and legs.
left_arm
¶
Add a left arm.
left_hand
¶
Add a left hand piece to the figure's left arm.
left_hand_item
¶
left_hand_item(
left_hand: Piece,
colour: ColourInput,
displacement: Vector,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add an item to the left hand.
right_arm
¶
Add a right arm.
right_hand
¶
Add a right hand piece to the figure's right arm.
right_hand_item
¶
right_hand_item(
right_hand: Piece,
colour: ColourInput,
displacement: Vector,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a right hand item.
left_leg
¶
Add a left leg.
left_shoe
¶
left_shoe(
left_leg: Piece,
colour: ColourInput,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a shoe on the left.
right_leg
¶
Add a right leg.
right_shoe
¶
right_shoe(
right_leg: Piece,
colour: ColourInput,
angle: Number = 0,
part: str | None = None,
) -> Piece | None
Add a shoe on the right.
Piece
dataclass
¶
A part with a defined colour, position, and rotation.
place
classmethod
¶
place(
part: str,
*,
colour: Colour | int = MAIN_COLOUR_CODE,
position: Vector | None = None,
matrix: Matrix | None = None,
group: Group | None = None,
suffix: str = DEFAULT_SUFFIX,
) -> Self
Create a piece keyword-first, defaulting to the origin and identity.
PreviewTransform
dataclass
¶
ProgressEvent
dataclass
¶
One progress update from a long-running library operation.
determinate
property
¶
Whether this event has a current value, total, and explicit unit.
RenderBackend
¶
RenderCapability
dataclass
¶
RenderResult
dataclass
¶
Output or diagnostics from one preview request.
RenderView
¶
RotationMode
¶
RotationStep
dataclass
¶
A parsed MLCad ROTSTEP boundary.
SectionShape
¶
Severity
¶
SkippedGeometry
dataclass
¶
SkippedOccurrenceGeometry
dataclass
¶
SnapCandidate
dataclass
¶
Compatible feature pair and the resulting moving-part placement.
SnapTransform
dataclass
¶
StudContact
dataclass
¶
Compatibility projection of one strict stud/receptacle feature match.
receptacle_feature
class-attribute
instance-attribute
¶
StudReference
dataclass
¶
A stud primitive placed by a part, in the part's own coordinates.
description
instance-attribute
¶
The primitive's header description, e.g. Stud Tube Open.
position
instance-attribute
¶
The primitive's origin -- for top studs, the centre of the stud base.
up
class-attribute
instance-attribute
¶
Image of the stud's local up direction (0, -1, 0) under the placing transforms; unit length under rigid placements.
is_receptacle
property
¶
Whether this primitive describes an underside/tube receiver.
is_placeholder
property
¶
Whether this is a drawing placeholder rather than a connector.
is_top_stud
property
¶
Whether this stud is an upward connector a brick can sit on.
Excludes underside tubes and placeholder primitives by description, and any stud whose placing transforms point it away from up (LDraw up is -Y), such as the sideways front stud of a headlight brick.
StudioConnectionLibrary
¶
Read the supported connectivity subset of a Studio JSON export.
A part row with an empty or absent connections list contributes no
authoritative evidence: heuristic and primitive features are kept and
coverage is unchanged. Explicit clear-to-empty is an LDCad SNAP_CLEAR
or override concern.
connections_for
¶
Return one part's row, or the document fallback when absent.
This single-part view carries per-part statistics, so summing it
over an assembly double-counts document evidence. Assembly
aggregation must use _part_feature_contribution per child and
_document_result_for once per root query instead.
Vector
dataclass
¶
A vector in 3D.
XAxis
¶
Bases: Axis
X-axis representation.
YAxis
¶
Bases: Axis
Y-axis representation.
ZAxis
¶
Bases: Axis
Z-axis representation.
analyze_model
¶
analyze_model(
model: Model,
*,
parts: Parts | None = None,
diagnostics: Iterable[Diagnostic] = (),
) -> ModelAnalysis
Traverse leaf occurrences once and reuse them for all derived views.
Cyclic submodel references (possible in tolerantly-loaded models) are
skipped rather than raising; each skipped reference surfaces as an
MPD_CYCLE diagnostic unless an equal one was already passed in via
diagnostics.
angular_alignment_within
¶
Return whether an absolute axis alignment is within a tolerance.
bill_of_materials
¶
bill_of_materials(
model: _ModelLike | None = None,
*,
parts: Parts | None = None,
occurrences: Iterable[ModelOccurrence] | None = None,
) -> list[BomRow]
Count leaf pieces by part and colour, expanding submodel references.
A submodel placed twice contributes its pieces twice. Submodel reference pieces themselves are expanded, never counted. Colour 16 (the main colour) inside a submodel is resolved to the colour the submodel was placed with. Descriptions and colour names are resolved when a parts catalog is given.
References only resolve against the given model's own submodel table.
To count one submodel of a larger model, pass
root.submodel_view(name) rather than a model taken straight from
Model.submodels — the latter treats nested submodel references as
leaf parts.
Part codes are counted case-insensitively; each row shows the code as first written in the model.
bounds_gap
¶
Return axis and Euclidean distance between two AABBs.
connection_residual
¶
Return centerline, axial, and orientation residuals for two features.
connections_compatible
¶
connections_compatible(
left: ConnectionFeature,
right: ConnectionFeature,
*,
radius_tolerance: float = 0.35,
) -> bool
Return whether two features are physically eligible to mate.
discover_libraries
¶
discover_libraries(
paths: Iterable[str | Path] | None = None,
*,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
) -> tuple[LibraryInspection, ...]
Discover valid and partial installations in configured/common locations.
download
¶
download(
*,
show_progress: bool = True,
version: str = COMPLETE_VERSION,
on_progress: ProgressCallback | None = None,
resume: bool = False,
cancellation: CancellationToken | None = None,
) -> str
Download and unpack an LDraw library version, generating parts.lst file.
The complete library comes from ldraw.org; versioned releases come from snapshot tags of the rienafairefr/ldraw-parts GitHub repository.
ensure_library
¶
ensure_library(
config: Config | None = None,
*,
version: str = COMPLETE_VERSION,
write_config: bool = False,
config_file: str | Path | None = None,
force_generate: bool = False,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
) -> LDrawSession
Ensure a configured library, generated package, and catalog index exist.
When the library is downloaded, config.ldraw_library_path is
updated in place on the caller's Config (persisted only when
write_config is true), and the process-global default import
configuration is replaced via LibraryImporter.set_config.
generate
¶
generate(
config: Config,
*,
force: bool = False,
on_progress: ProgressCallback | None = None,
fingerprint: str | None = None,
cancellation: CancellationToken | None = None,
) -> None
Generate the library from configuration.
inspect_library
¶
Inspect a candidate installation without building its catalog.
inspect_model
¶
inspect_model(
model: Model,
parts: Parts,
*,
occurrences: Iterable[ModelOccurrence] | None = None,
page_marker_prefix: str = DEFAULT_PAGE_MARKER_PREFIX,
) -> ModelInspection
Inspect leaf occurrences using recursively expanded exact geometry.
iter_instruction_issues
¶
iter_instruction_issues(
document: InstructionDocument,
*,
max_parts: int | None = None,
) -> Iterator[InstructionIssue]
Yield structural and semantic issues in document.
iter_ldr_issues
¶
iter_ldr_issues(
path: Path | ModelLoadResult, parts: Parts | None = None
) -> Iterator[ValidationIssue]
Yield the issues found in an LDraw model or part file, in line order.
Malformed lines, unparseable colour values, and (when a parts catalog with colour definitions is given) unknown part references and colour codes are errors. Suspicious-but-legal constructs — legacy dithered colours, non-orthonormal or singular transformation matrices, and unknown bang meta-commands — are warnings.
Unreadable or non-UTF-8 files do not raise; they yield an
IO_READ_FAILED or IO_DECODE_FAILED error diagnostic with
line_number=None. Issues are yielded sorted by line number, with
file-level diagnostics (line_number=None) first.
load_model
¶
load_model(
path: Path | str,
parts: Parts | None = None,
*,
tolerant: bool = True,
) -> ModelLoadResult
Read, parse, and validate a model without throwing for data failures.
model_bounds
¶
Return the true transformed bounds for model in LDraw units.
parse_model
¶
Parse LDraw document text into a Model.
A document without 0 FILE sections becomes a single model. In an MPD
document the first section becomes the returned root model and later
sections become its submodels, resolvable via Model.submodel_for.
parse_model_result
¶
parse_model_result(
text: str,
*,
name: str = "",
source: Path | str | None = None,
parts: Parts | None = None,
tolerant: bool = True,
) -> ModelLoadResult
Parse and validate text once, optionally retaining a partial model.
plan_download
¶
plan_download(
version: str = COMPLETE_VERSION,
*,
cache_path: str | Path | None = None,
cancellation: CancellationToken | None = None,
) -> DownloadPlan
Inspect remote size/resume support and local archive integrity.
prepare_catalog
¶
prepare_catalog(
config: Config | None = None,
*,
capabilities: Iterable[LDrawCapability] = (
LDrawCapability.CATALOG,
),
connection_shadows: Iterable[str | Path] = (),
studio_metadata: Iterable[str | Path] = (),
force: bool = False,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
) -> CatalogPreparationResult
Prepare requested configured data and return a structured report.
render_capabilities
¶
Detect optional renderers without invoking them.
render_preview
¶
render_preview(
source: str | Path,
*,
view: RenderView = RenderView.ISOMETRIC,
size: tuple[int, int] = (800, 600),
backend: RenderBackend | None = None,
output: str | Path | None = None,
cache_path: str | Path | None = None,
refresh: bool = False,
on_progress: ProgressCallback | None = None,
cancellation: CancellationToken | None = None,
) -> RenderResult
Render one view, using a content-addressed PNG cache when possible.
The cache key covers the top-level source bytes, the resolved renderer
executable path, and the full render command (backend, view angles, size,
and renderer options). Files referenced by the source (submodels and
sidecar part files) and the parts-library state are NOT part of the key,
so edits to them do not invalidate cached previews; pass refresh=True
to skip the cache read and force a re-render (the fresh image is still
written back to the cache). The managed default cache evicts PNGs older
than 90 days and caps retained data at 512 MiB, checking at most once
per hour; caller-provided cache directories are never pruned
automatically.
snap_transform
¶
Return a rigid transform placing moving onto target.
Centered cylindrical interfaces are direction-symmetric, so their target frame is flipped when that gives the smaller axis rotation; non-centered profiles extend one-sided and always mate axis-to-axis. Cross-section roll is preserved for axle profiles. Candidate frames are matched to the moving frame's handedness, so the delta is always a proper rotation and a part placed with a mirroring matrix is never reflected.
rows_to_csv
¶
Serialize rows to CSV text with a header line.
rows_to_json
¶
Serialize rows to a JSON array of objects.
Config
¶
Configuration settings for pyldraw.
ldraw_library_path
instance-attribute
¶
ldraw_library_path: str = (
ldraw_library_path
if ldraw_library_path is not None
else str(Path(get_cache_dir()) / "complete")
)
generated_path
instance-attribute
¶
generated_path: str = (
generated_path
if generated_path is not None
else str(Path(get_data_dir()) / "generated")
)
load
classmethod
¶
Load configuration from YAML file or create default configuration.
A missing file yields the defaults; an unreadable or malformed
file raises ConfigLoadError naming the path and the problem.
write
¶
Write the config atomically with a unique sibling temporary file.
NoGeometryError
¶
Bases: PartError
The part (including its subfiles) draws no geometry at all.
add_context
¶
Extend the message with file/line context, at most once.
PartNotFoundError
¶
Bases: PartError
Part was not found as expected.
add_context
¶
Extend the message with file/line context, at most once.
UnknownSubmodelError
¶
Bases: PartError
The requested submodel name is not in this model's submodel table.
part_bounding_box
¶
Axis-aligned bounding box of a part's geometry, in LDU.
Subfiles are resolved recursively and the expanded drawable points are transformed before the box is folded, including under oblique transforms. Unresolvable subfiles are skipped with a warning.
Raises PartNotFoundError for an unknown code and
NoGeometryError when the part draws nothing. Read failures
(OSError/UnicodeError) on the part's own file are tolerated
the same way as unresolvable subfiles: the file contributes no
geometry, so the query raises NoGeometryError rather than the
underlying IO error.
part_studs
¶
All stud primitives a part places, in the part's own coordinates.
Stud groups and subparts are expanded down to individual stud*
primitives; recursion stops at each stud so nothing is counted twice.
Filter with StudReference.is_top_stud (or use
Parts.stud_positions) to keep only upward connectors.
symbol_description
¶
Return the description that generated symbol names derive from.
Minifig part descriptions drop their Minifig prefix so symbols in
the minifig/minifig_* modules read Torso, not
MinifigTorso; every other description passes through unchanged.
module_path
¶
Return the generated module path containing entry, if any.
suggested_import
¶
Return an import statement for entry in the generated library.
symbol_name
¶
Return the generated Python symbol name for a catalog entry.
symbol_name_for_description
¶
Return the generated Python symbol for an LDraw description.