go3mf

package module
v0.24.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2023 License: BSD-2-Clause Imports: 20 Imported by: 5

README

PkgGoDev Build Status Go Report Card Coverage Status License

go3mf

The 3D Manufacturing Format (3MF) is a 3D printing format that allows design applications to send full-fidelity 3D models to a mix of other applications, platforms, services and printers. The 3MF specification allows companies to focus on innovation, rather than on basic interoperability issues, and it is engineered to avoid the problems associated with other 3D file formats. Detailed info about the 3MF specification can be fint at 3mf.io.

Features

  • High parsing speed and moderate memory consumption
  • Complete 3MF Core spec implementation.
  • Clean API.
  • STL importer
  • Spec conformance validation
  • Robust implementation with full coverage and validated against real cases.
  • Extensions
    • Support custom and private extensions.
    • Support lossless decoding and encoding of unknown extensions.
    • spec_production.
    • spec_slice.
    • spec_beamlattice.
    • spec_materials, missing the display resources.

Examples

Read from file
package main

import (
    "fmt"

    "github.com/hpinc/go3mf"
)

func main() {
    var model go3mf.Model
    r, _ := go3mf.OpenReader("/testdata/cube.3mf")
    r.Decode(&model)
    for _, item := range model.Build.Items {
      fmt.Println("item:", *item)
      obj, _ := model.FindObject(item.ObjectPath(), item.ObjectID)
      fmt.Println("object:", *obj)
      if obj.Mesh != nil {
        for _, t := range obj.Mesh.Triangles.Triangle {
          fmt.Println(t)
        }
        for _, v := range obj.Mesh.Vertices.Vertex {
          fmt.Println(v.X(), v.Y(), v.Z())
        }
      }
    }
}
Read from HTTP body
package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "github.com/hpinc/go3mf"
)

func main() {
    resp, _ := http.Get("zip file url")
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    var model go3mf.Model
    r, _ := go3mf.NewDecoder(bytes.NewReader(body), int64(len(body)))
    r.Decode(&model)
    fmt.Println(model)
}
Write to file
package main

import (
    "fmt"
    "os"

    "github.com/hpinc/go3mf"
)

func main() {
    var model go3mf.Model
    w, _ := go3mf.CreateWriter("/testdata/cube.3mf")
    w.Encode(&model)
    w.Close()
}
Spec usage

Specs are automatically registered when importing them as a side effect of the init function.

package main

import (
    "fmt"

    "github.com/hpinc/go3mf"
    "github.com/hpinc/go3mf/material"
    "github.com/hpinc/go3mf/production"
)

func main() {
    var model go3mf.Model
    r, _ := go3mf.OpenReader("/testdata/cube.3mf")
    r.Decode(&model)
    fmt.Println(production.GetBuildAttr(&model.Build).UUID)

    model.Resources.Assets = append(model.Resources.Assets, &materials.ColorGroup{
      ID: 10, Colors: []color.RGBA{{R: 255, G: 255, B: 255, A: 255}},
    }
}

Documentation

Index

Constants

View Source
const (
	// Namespace is the canonical name of this extension.
	Namespace = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"

	// RelType3DModel is the canonical 3D model relationship type.
	RelType3DModel = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
	// RelTypeThumbnail is the canonical thumbnail relationship type.
	RelTypeThumbnail = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"
	// RelTypePrintTicket is the canonical print ticket relationship type.
	RelTypePrintTicket = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket"
	// RelTypeMustPreserve is the canonical must preserve relationship type.
	RelTypeMustPreserve = "http://schemas.openxmlformats.org/package/2006/relationships/mustpreserve"

	// DefaultModelPath is the recommended root model part name.
	DefaultModelPath = "/3D/3dmodel.model"
	// DefaultPrintTicketName is the recommended print ticket part name.
	DefaultPrintTicketName = "/3D/Metadata/Model_PT.xml"
	// Default3DTexturesDir is the recommended directory for 3D textures.
	Default3DTexturesDir = "/3D/Textures/"
	// Default3DOtherDir is the recommended directory for non-standard parts.
	Default3DOtherDir = "/3D/Other/"
	// DefaultMetadataDir is the recommended directory for standard metadata.
	DefaultMetadataDir = "/Metadata/"

	// ContentType3DModel is the 3D model content type.
	ContentType3DModel = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"
	// ContentTypePrintTicket is the print ticket content type.
	ContentTypePrintTicket = "application/vnd.ms-printing.printticket+xml"
)

Variables

This section is empty.

Functions

func MarshalModel

func MarshalModel(m *Model) ([]byte, error)

MarshalModel returns the XML encoding of m.

func UnmarshalModel

func UnmarshalModel(data []byte, model *Model) error

UnmarshalModel fills a model with the data of a root model file using not strict mode.

Types

type Asset

type Asset interface {
	XMLName() xml.Name
	Identify() uint32
}

Asset defines build resource.

type Attachment

type Attachment struct {
	Stream      io.Reader
	Path        string
	ContentType string
}

Attachment defines the Model Attachment.

type Base

type Base struct {
	Name    string
	Color   color.RGBA
	AnyAttr spec.AnyAttr
}

Base defines the Model Base Material Resource. A model material resource is an in memory representation of the 3MF material resource object.

type BaseMaterials

type BaseMaterials struct {
	ID        uint32
	Materials []Base
	AnyAttr   spec.AnyAttr
}

BaseMaterials defines a slice of Base.

func (*BaseMaterials) Identify

func (r *BaseMaterials) Identify() uint32

Identify returns the unique ID of the resource.

func (*BaseMaterials) Len

func (r *BaseMaterials) Len() int

Len returns the materials count.

func (*BaseMaterials) Marshal3MF

func (r *BaseMaterials) Marshal3MF(x spec.Encoder, _ *xml.StartElement) error

func (*BaseMaterials) Validate

func (r *BaseMaterials) Validate(m *Model, path string) error

Validate validates the base materia is compliant with the 3MF specs.

func (BaseMaterials) XMLName added in v0.24.0

func (BaseMaterials) XMLName() xml.Name

XMLName returns the xml identifier of the resource.

type Box

type Box struct {
	Min Point3D
	Max Point3D
}

Box defines a box in the 3D space.

type Build

type Build struct {
	Items   []*Item
	AnyAttr spec.AnyAttr
}

Build contains one or more items to manufacture as part of processing the job.

type ChildModel

type ChildModel struct {
	Resources     Resources
	Relationships []Relationship
	Any           spec.Any
}

ChildModel repreents de content of a non-root model file.

It is not supported by the core spec but a common concept for multiple official specs. The relationships are usually managed by the extensions themself, but they are usefull to reference custom attachments.

type Component

type Component struct {
	ObjectID  uint32
	Transform Matrix
	AnyAttr   spec.AnyAttr
}

A Component is an in memory representation of the 3MF component.

func (*Component) HasTransform

func (c *Component) HasTransform() bool

HasTransform returns true if the transform is different than the identity.

func (*Component) ObjectPath

func (c *Component) ObjectPath(defaultPath string) string

ObjectPath search an extension attribute with an ObjectPath function that return a non empty path. Else returns the default path.

type Components

type Components struct {
	Component []*Component
	AnyAttr   spec.AnyAttr
}

A Components is an in memory representation of the 3MF components.

type Decoder

type Decoder struct {
	Strict bool
	// contains filtered or unexported fields
}

Decoder implements a 3mf file decoder.

func NewDecoder

func NewDecoder(r io.ReaderAt, size int64) *Decoder

NewDecoder returns a new Decoder reading a 3mf file from r.

func (*Decoder) Decode

func (d *Decoder) Decode(model *Model) error

Decode reads the 3mf file and unmarshall its content into the model.

func (*Decoder) DecodeContext

func (d *Decoder) DecodeContext(ctx context.Context, model *Model) error

DecodeContext reads the 3mf file and unmarshall its content into the model.

type Encoder

type Encoder struct {
	FloatPrecision int
	// contains filtered or unexported fields
}

An Encoder writes Model data to an output stream.

See the documentation for strconv.FormatFloat for details about the FloatPrecision behaviour.

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.

func (*Encoder) Encode

func (e *Encoder) Encode(m *Model) error

Encode writes the XML encoding of m to the stream.

type Extension

type Extension struct {
	Namespace  string
	LocalName  string
	IsRequired bool
}

type Item

type Item struct {
	ObjectID   uint32
	Transform  Matrix
	PartNumber string
	Metadata   MetadataGroup
	AnyAttr    spec.AnyAttr
}

A Item is an in memory representation of the 3MF build item.

func (*Item) HasTransform

func (b *Item) HasTransform() bool

HasTransform returns true if the transform is different than the identity.

func (*Item) ObjectPath

func (b *Item) ObjectPath() string

ObjectPath search an extension attribute with an ObjectPath function that return a non empty path. Else returns an empty path.

type Matrix

type Matrix [16]float32

Matrix is a 4x4 matrix in row major order.

m[4*r + c] is the element in the r'th row and c'th column.

func Identity

func Identity() Matrix

Identity returns the 4x4 identity matrix. The identity matrix is a square matrix with the value 1 on its diagonals. The characteristic property of the identity matrix is that any matrix multiplied by it is itself. (MI = M; IN = N)

func (Matrix) Mul

func (m1 Matrix) Mul(m2 Matrix) Matrix

Mul performs a "matrix product" between this matrix and another matrix.

func (Matrix) Mul2D

func (m1 Matrix) Mul2D(v Point2D) Point2D

Mul2D performs a "matrix product" between this matrix and another 2D point.

func (Matrix) Mul3D

func (m1 Matrix) Mul3D(v Point3D) Point3D

Mul3D performs a "matrix product" between this matrix and another 3D point.

func (Matrix) MulBox

func (m1 Matrix) MulBox(b Box) Box

MulBox performs a "matrix product" between this matrix and a box

func (Matrix) String

func (m1 Matrix) String() string

String returns the string representation of a Matrix.

func (Matrix) Translate

func (m1 Matrix) Translate(x, y, z float32) Matrix

Translate returns a matrix with a relative translation applied.

type Mesh

type Mesh struct {
	Vertices  Vertices
	Triangles Triangles
	AnyAttr   spec.AnyAttr
	Any       spec.Any
}

A Mesh is an in memory representation of the 3MF mesh object. Each node and face have an ID, which allows to identify them. Each face have an orientation (i.e. the face can look up or look down) and have three nodes. The orientation is defined by the order of its nodes.

func (*Mesh) BoundingBox

func (m *Mesh) BoundingBox() Box

BoundingBox returns the bounding box of the mesh.

func (*Mesh) ValidateCoherency

func (m *Mesh) ValidateCoherency() error

ValidateCoherency checks that the mesh is non-empty, manifold and oriented.

type MeshBuilder

type MeshBuilder struct {
	// True to automatically check if a node with the same coordinates already exists in the mesh
	// when calling AddVertex. If it exists, the return value will be the existing node and no node will be added.
	// Using this option produces an speed penalty.
	CalculateConnectivity bool
	// Do not modify the pointer to Mesh once the build process has started.
	Mesh *Mesh
	// contains filtered or unexported fields
}

MeshBuilder is a helper that creates mesh following a configurable criteria. It must be instantiated using NewMeshBuilder.

func NewMeshBuilder

func NewMeshBuilder(m *Mesh) *MeshBuilder

NewMeshBuilder returns a new MeshBuilder.

func (*MeshBuilder) AddVertex

func (mb *MeshBuilder) AddVertex(node Point3D) uint32

AddVertex adds a node the the mesh at the target position.

type Metadata

type Metadata struct {
	Name     xml.Name
	Value    string
	Type     string
	Preserve bool
}

Metadata item is an in memory representation of the 3MF metadata, and can be attached to any 3MF model node.

type MetadataGroup added in v0.24.0

type MetadataGroup struct {
	Metadata []Metadata
	AnyAttr  spec.AnyAttr
}

type Model

type Model struct {
	Path              string
	Language          string
	Units             Units
	Thumbnail         string
	Resources         Resources
	Build             Build
	Attachments       []Attachment
	Extensions        []Extension // space -> spec
	Metadata          []Metadata
	Childs            map[string]*ChildModel // path -> child
	RootRelationships []Relationship
	Relationships     []Relationship
	Any               spec.Any
	AnyAttr           spec.AnyAttr
}

A Model is an in memory representation of the 3MF file.

If path is empty, the default path '/3D/3dmodel.model' will be used. The relationships are usually managed by the extensions themself, but they are usefull to reference custom attachments. Childs keys cannot be an empty string. RootRelationships are the OPC root relationships.

func (*Model) BoundingBox

func (m *Model) BoundingBox() Box

BoundingBox returns the bounding box of the model.

func (*Model) FindAsset

func (m *Model) FindAsset(path string, id uint32) (Asset, bool)

FindAsset returns the resource with the target path and ID.

func (*Model) FindObject

func (m *Model) FindObject(path string, id uint32) (*Object, bool)

FindObject returns the object with the target path and ID.

func (*Model) FindResources

func (m *Model) FindResources(path string) (*Resources, bool)

FindResources returns the resource associated with path.

func (*Model) PathOrDefault

func (m *Model) PathOrDefault() string

PathOrDefault returns Path if not empty, else DefaultModelPath.

func (*Model) Validate

func (m *Model) Validate() error

Validate checks that the model is conformant with the 3MF specs.

func (*Model) ValidateCoherency

func (m *Model) ValidateCoherency() error

ValidateCoherency checks that all the mesh are non-empty, manifold and oriented.

func (*Model) WalkAssets

func (m *Model) WalkAssets(fn func(string, Asset) error) error

WalkAssets walks the assets of the root and child models, calling fn for asset and stopping if fn returns an error.

The child models are first walked in lexical order and then the root model is walked. The root model path is always empty, regardless of the defined model path.

func (*Model) WalkObjects

func (m *Model) WalkObjects(fn func(string, *Object) error) error

WalkObjects walks the objects of the root and child models, calling fn for object and stopping if fn returns an error.

The child models are first walked in lexical order and then the root model is walked. The root model path is always empty, regardless of the defined model path.

type Object

type Object struct {
	ID         uint32
	Name       string
	PartNumber string
	Thumbnail  string
	PID        uint32
	PIndex     uint32
	Type       ObjectType
	Metadata   MetadataGroup
	Mesh       *Mesh
	Components *Components
	AnyAttr    spec.AnyAttr
}

An Object is an in memory representation of the 3MF model object.

func (*Object) Validate

func (r *Object) Validate(m *Model, path string) error

Validate validates that the object is compliant with 3MF specs, except for the mesh coherency.

type ObjectType

type ObjectType int8

ObjectType defines the allowed object types.

const (
	ObjectTypeModel ObjectType = iota
	ObjectTypeOther
	ObjectTypeSupport
	ObjectTypeSolidSupport
	ObjectTypeSurface
)

Supported object types.

func (ObjectType) String

func (o ObjectType) String() string

type Point2D

type Point2D [2]float32

Point2D defines a node of a slice as an array of 2 coordinates: x and y.

func (Point2D) X

func (n Point2D) X() float32

X returns the x coordinate.

func (Point2D) Y

func (n Point2D) Y() float32

Y returns the y coordinate.

type Point3D

type Point3D [3]float32

Point3D defines a node of a mesh as an array of 3 coordinates: x, y and z.

func (Point3D) X

func (v1 Point3D) X() float32

X returns the x coordinate.

func (Point3D) Y

func (v1 Point3D) Y() float32

Y returns the y coordinate.

func (Point3D) Z

func (v1 Point3D) Z() float32

Z returns the z coordinate.

type ReadCloser

type ReadCloser struct {
	Decoder
	// contains filtered or unexported fields
}

ReadCloser wrapps a Decoder than can be closed.

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the 3MF file specified by name and return a ReadCloser.

func (*ReadCloser) Close

func (r *ReadCloser) Close() error

Close closes the 3MF file, rendering it unusable for I/O.

type Relationship

type Relationship struct {
	Path string
	Type string
	ID   string
}

Relationship defines a dependency between the owner of the relationsip and the attachment referenced by path. ID is optional, if not set a random value will be used when encoding.

type Resources

type Resources struct {
	Assets  []Asset
	Objects []*Object
	AnyAttr spec.AnyAttr
}

The Resources element acts as the root element of a library of constituent pieces of the overall 3D object definition.

func (*Resources) FindAsset

func (rs *Resources) FindAsset(id uint32) (Asset, bool)

FindAsset returns the resource with the target ID.

func (*Resources) FindObject

func (rs *Resources) FindObject(id uint32) (*Object, bool)

FindObject returns the resource with the target ID.

func (*Resources) UnusedID

func (rs *Resources) UnusedID() uint32

UnusedID returns the lowest unused ID.

type Triangle

type Triangle struct {
	V1, V2, V3 uint32
	PID        uint32
	P1, P2, P3 uint32
	AnyAttr    spec.AnyAttr
}

Triangle defines a triangle of a mesh.

The 7 elements are: v1,v2,v3,pid,p1,p2,p3.

type Triangles added in v0.24.0

type Triangles struct {
	Triangle []Triangle
	AnyAttr  spec.AnyAttr
}

type Units

type Units uint8

Units define the allowed model units.

const (
	UnitMillimeter Units = iota
	UnitMicrometer
	UnitCentimeter
	UnitInch
	UnitFoot
	UnitMeter
)

Supported units.

func (Units) String

func (u Units) String() string

type UnknownAsset added in v0.23.0

type UnknownAsset struct {
	spec.UnknownTokens
	// contains filtered or unexported fields
}

UnknownAsset wraps a spec.UnknownTokens to fulfill the Asset interface.

func (UnknownAsset) Identify added in v0.23.0

func (u UnknownAsset) Identify() uint32

type Vertices added in v0.24.0

type Vertices struct {
	Vertex  []Point3D
	AnyAttr spec.AnyAttr
}

type WriteCloser added in v0.22.2

type WriteCloser struct {
	Encoder
	// contains filtered or unexported fields
}

WriteCloser wrapps an Encoder than can be closed.

func CreateWriter added in v0.22.2

func CreateWriter(name string) (*WriteCloser, error)

CreateWriter will create the 3MF file specified by name and return a WriteCloser.

func (*WriteCloser) Close added in v0.22.2

func (w *WriteCloser) Close() error

Close closes the 3MF file, rendering it unusable for I/O.

Directories

Path Synopsis
importer
stl
internal
xml

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL