Crate dae_parser

Source
Expand description

§Collada parser

This is a parser for the Collada (.dae) format, used for interchange between 3D renderers and games. Compared to the collada crate, this crate attempts to more directly represent the Collada data model, and it is also significantly more complete. It supports both reading and writing.

§Usage

The main entry point is the Document type, which has a FromStr implementation to convert literal strings / slices, or Document::from_file to read from a .dae file on disk.

Collada documents are parsed eagerly, validating everything according to the COLLADA schema. Once parsed, the data structures (structs and enums) can be navigated directly, as all the data structures are public, and reflect the XML schema closely.

This library implements only version 1.4.1 of the Collada spec, although it may be expanded in the future. (Please open an issue or PR if you find anything missing from the spec, or if you have a use case for a later version.)

use std::str::FromStr;
use dae_parser::*;

let dae_file = r##"<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
  <asset>
    <created>1970-01-01T00:00:00Z</created>
    <modified>1970-01-01T00:00:00Z</modified>
  </asset>
  <library_geometries>
    <geometry id="Cube-mesh" name="Cube">
      <mesh>
        <source id="Cube-mesh-positions">
          <float_array id="Cube-mesh-positions-array" count="18">
            1 1 1 1 -1 1 1 -1 -1 -1 1 1 -1 -1 1 -1 -1 -1
          </float_array>
          <technique_common>
            <accessor source="#Cube-mesh-positions-array" count="6" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <vertices id="Cube-mesh-vertices">
          <input semantic="POSITION" source="#Cube-mesh-positions"/>
        </vertices>
        <triangles material="Material-material" count="4">
          <input semantic="VERTEX" source="#Cube-mesh-vertices" offset="0"/>
          <p>3 1 0 1 5 2 3 4 1 1 4 5</p>
        </triangles>
      </mesh>
    </geometry>
  </library_geometries>
</COLLADA>"##;

let document = Document::from_str(dae_file).unwrap();
let cube = document.local_map::<Geometry>().unwrap().get_str("Cube-mesh").unwrap();
let sources_map = document.local_map::<Source>().unwrap();
let vertices_map = document.local_map::<Vertices>().unwrap();
// sources.get("Cube-mesh-positions").unwrap();
assert_eq!(cube.id.as_ref().unwrap(), "Cube-mesh");
let mesh = cube.element.as_mesh().unwrap();
let tris = mesh.elements[0].as_triangles().unwrap();
assert_eq!(
    tris.data.as_deref().unwrap(),
    &[3, 1, 0, 1, 5, 2, 3, 4, 1, 1, 4, 5]
);
assert_eq!(tris.inputs[0].semantic, Semantic::Vertex);
let vertices = vertices_map.get_raw(&tris.inputs[0].source).unwrap();
assert_eq!(vertices.id, "Cube-mesh-vertices");
let source = sources_map
    .get_raw(&vertices.position_input().source)
    .unwrap();
assert_eq!(source.id.as_deref(), Some("Cube-mesh-positions"));

§License

Licensed under either of

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Modules§

geom
Contains functions for reading vertex and other data out of the geometry types, like Mesh.
local_map
Contains the LocalMap and LocalMaps types, used to resolve internal ID references.
source
Contains functions for reading data out of a Source.

Structs§

Accessor
Describes a stream of values from an array data source.
Address
An unparsed COLLADA target address. See the “Address Syntax” section in Chapter 3: Schema concepts of the COLLADA spec.
AmbientLight
Describes an ambient light source.
Animation
Categorizes the declaration of animation information.
AnimationClip
Defines a section of a set of animation curves to be used together as an animation clip.
Annotate
Adds a strongly typed annotation remark to the parent object.
Asset
Defines asset-management information regarding its parent element.
Attachment
Defines an attachment frame, to a rigid body or a node, within a rigid constraint.
BindM
Binds values to uniform inputs of a shader or binds values to effect parameters upon instantiation. In the COLLADA spec, this element is called “<bind> (material)”.
BindMaterial
Binds a specific material to a piece of geometry, binding varying and uniform parameters at the same time.
BindVertexInput
Binds geometry vertex inputs to effect vertex inputs upon instantiation.
Blinn
Produces a specularly shaded surface with a Blinn BRDF approximation.
BoolArray
Stores a homogenous array of Boolean values.
BoxShape
Declares an axis-aligned, centered box primitive. (Note: The type is not called Box to avoid the name clash with the Rust builtin type.)
Camera
Declares a view of the visual scene hierarchy or scene graph. The camera contains elements that describe the camera’s optics and imager.
Capsule
Declares a capsule primitive that is centered on and aligned with the local y axis.
Channel
Declares an output channel of an animation.
CommonData
The extra data in a TechniqueFx as the child of ProfileCommon.
ConstantFx
Produces a constantly shaded surface that is independent of lighting.
Contributor
Defines authoring information for asset management.
ControlVertices
Describes the control vertices (CVs) of a spline.
Controller
Categorizes the declaration of generic control information.
Cylinder
Declares a cylinder primitive that is centered on, and aligned with, the local y axis.
DirectionalLight
Describes a directional light source.
Document
A Collada document. Represents the <COLLADA> root node.
Effect
Provides a self-contained description of a COLLADA effect.
EffectSetParam
Assigns a new value to a previously defined parameter.
Element
A struct representing a DOM Element.
EvaluateScene
Declares information specifying how to evaluate a VisualScene.
Extra
Provides arbitrary additional information about or related to its parent element.
FloatArray
Stores a homogenous array of floating-point values.
ForceField
Provides a general container for force fields.
FormatHint
This element describes the important features intended by the author so that the application can pick a format that best represents what the author wanted.
Geom
The common data for the geometry types:
Geometry
Describes the visual shape and appearance of an object in a scene.
IdRefArray
Stores a homogenous array of ID reference values.
Image
Declares the storage for the graphical representation of an object.
Imager
Represents the image sensor of a camera (for example, film or CCD).
Input
Declares the input semantics of a data source and connects a consumer to that source. In the COLLADA spec this is called “<input> (unshared)”.
InputList
Wraps a group of inputs and precalculates the depth field.
InputS
Declares the input semantics of a data source and connects a consumer to that source. In the COLLADA spec this is called “<input> (shared)”.
Instance
Instantiates a COLLADA material resource, possibly applying transformations or effects to the object.
InstanceControllerData
Extra data associated to Instance<Controller>.
InstanceEffectData
Extra data associated to Instance<Effect>.
InstanceGeometryData
Extra data associated to Instance<Geometry>.
InstanceMaterial
Instantiates a COLLADA material resource.
InstancePhysicsModelData
Extra data associated to Instance<PhysicsModel>.
InstanceRigidBody
Instantiates an object described by a RigidBody within an Instance<PhysicsModel>.
InstanceRigidBodyCommon
Specifies the rigid-body information for the common profile that all COLLADA implementations must support.
InstanceRigidConstraint
Instantiates an object described by a RigidConstraint within an Instance<PhysicsModel>.
IntArray
Stores a homogenous array of integer values.
ItemIter
An iterator over all T elements for a ParseLibrary type T, returned by Document::iter.
Joints
Declares the association between joint nodes and attribute data.
Lambert
Produces a diffuse shaded surface that is independent of lighting.
Library
Declares a module of elements of type T.
LibraryIter
An iterator over all Library<T> elements for a particular T, returned by Document::library_iter.
Light
Declares a light source that illuminates a scene.
Limits
A set of min/max limits used for both linear and angular constraints.
LineGeom
The data for a Lines element.
LineStripGeom
The data for a LineStrips element.
LocalMap
A map for looking up elements of type T in the document by ID.
LocalMaps
A data structure which maintains LocalMaps for every applicable type. If you need to use Document::local_map for many different types, it may be more efficient to use this type, which calculates all maps in a single pass.
LookAt
Contains a position and orientation transformation suitable for aiming a camera.
Material
Describes the visual appearance of a geometric object.
Matrix
Describes transformations that embody mathematical changes to points within a coordinate system or the coordinate system itself.
Mesh
Describes basic geometric meshes using vertex and primitive information.
Morph
Describes the data required to blend between sets of static meshes.
NameArray
Stores a homogenous array of symbolic name values.
NewParam
Instruction to create a new, named Param object in the FX Runtime, assign it a type, an initial value, and additional attributes at declaration time.
Node
Embodies the hierarchical relationship of elements in a scene.
Optics
Represents the apparatus on a camera that projects the image onto the image sensor.
Orthographic
Describes the field of view of an orthographic camera.
Param
Declares parametric information for its parent element.
Perspective
Describes the field of view of a perspective camera.
Phong
Produces a specularly shaded surface where the specular reflection is shaded according the Phong BRDF approximation.
PhysicsMaterial
Defines the physical properties of an object.
PhysicsMaterialCommon
Specifies physics-material information for the common profile that all COLLADA implementations must support.
PhysicsModel
Allows for building complex combinations of rigid bodies and constraints that may be instantiated multiple times.
PhysicsScene
Specifies an environment in which physical objects are instantiated and simulated.
PhysicsSceneCommon
Specifies physics-scene information for the common profile that all COLLADA implementations must support.
Plane
Defines an infinite plane primitive.
PointLight
Describes a point light source.
PolyListGeom
The data for a PolyList element.
PolygonGeom
The data for a Polygons element.
PolygonHole
The data for an individual polygon-with-hole.
ProfileCG
The <profile_CG> element and its contents are unsupported and represented here as a raw XML element.
ProfileCommon
Opens a block of platform-independent declarations for the common, fixed-function shader.
ProfileGLES
The <profile_GLES> element and its contents are unsupported and represented here as a raw XML element.
ProfileGLSL
The <profile_GLSL> element and its contents are unsupported and represented here as a raw XML element.
Ref
A wrapper around a base type A to indicate that the value is pointing to a value of type T.
Render
Describes one effect pass to evaluate a scene.
RigidBody
Describes simulated bodies that do not deform.
RigidBodyCommon
Specifies rigid-body information for the common profile that every COLLADA implmentation must support.
RigidConstraint
Connects components, such as RigidBody, into complex physics models with moveable parts.
RigidConstraintCommon
Specifies rigid-constraint information for the common profile that all COLLADA implementations must support.
Rotate
Specifies how to rotate an object around an axis.
Sampler
Declares an interpolation sampling function for an animation.
Sampler2D
Declares a two-dimensional texture sampler.
Scale
Specifies how to change an object’s size.
Scene
Embodies the entire set of information that can be visualized from the contents of a COLLADA resource.
Shape
Describes components of a RigidBody.
Skew
Specifies how to deform an object along one axis.
Skin
Contains vertex and primitive information sufficient to describe blend-weight skinning.
Source
Declares a data repository that provides values according to the semantics of an Input element that refers to it.
Sphere
Describes a centered sphere primitive.
Spline
Describes a multisegment spline with control vertex (CV) and segment information.
SpotLight
Describes a spot light source.
Spring
A spring constraint, used for both linear and angular constraints.
Surface
Declares a resource that can be used both as the source for texture samples and as the target of a rendering pass.
TaperedCapsule
Describes a tapered capsule primitive that is centered on, and aligned with, the local y axis.
TaperedCylinder
Describes a tapered cylinder primitive that is centered on and aligned with the local y axis.
Targets
Declares morph targets, their weights, and any user-defined attributes associated with them.
Technique
Declares the information used to process some portion of the content. Each technique conforms to an associated profile. In the COLLADA spec, this element is called “<technique> (core)”.
TechniqueFx
Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method.
TechniqueHint
Adds a hint for a platform of which technique to use in this effect.
Texture
A color parameter referencing a texture.
Translate
Changes the position of an object in a local coordinate system.
TriFanGeom
The data for a TriFans element.
TriStripGeom
The data for a TriStrips element.
TriangleGeom
The data for a Triangles element.
Unit
Defines unit of distance for COLLADA elements and objects. This unit of distance applies to all spatial measurements within the scope of Asset’s parent element, unless overridden by a more local Asset / Unit.
VertexWeights
Describes the combination of joints and weights used by a skin.
Vertices
Declares the attributes and identity of mesh-vertices.
VisualScene
Embodies the entire set of information that can be visualized from the contents of a COLLADA resource.
WithSid
A struct that attaches an optional SID to a shader parameter.

Enums§

AnnotType
A strongly typed value that represents the VALUE in an object of the form SYMBOL = VALUE.
ArrayElement
A data array element.
ColorParam
A type that describes color attributes of fixed-function shader elements inside ProfileCommon effects.
ControlElement
The element that contains control data.
DefInstance
Either an instance of a T, or a directly inlined T object.
Error
The main error type used by this library.
FloatParam
A type that describes the scalar attributes of fixed-function shader elements inside ProfileCommon effects.
GeometryElement
An element that describes geometric data.
ImageParam
An Image or NewParam element.
ImageSource
A specification of the source of data for an image.
LibraryElement
A library element, which can be a module of any of the kinds supported by COLLADA.
LightKind
The kind of light being described.
MaybeDateTime
Collada spec says that created and modified times should follow ISO 8601, but chrono asserts that this means that timezones are required and Blender doesn’t seem to add them. To avoid crashing, we store the unparsed date as a string.
Modifier
Additional information about the volatility or linkage of a parameter.
MorphMethod
Which blending technique to use.
NodeType
The type of a Node element.
ParamType
A parameter’s type. We do not have full support here, but unknown types can be retrieved in the Other variant.
Primitive
A collection of primitive elements.
Profile
A <profile_*> element.
ProjectionType
The projection type of the camera.
RigidTransform
A RigidBody transform is a subset of the full set of Transforms which restricts to euclidean transformations (translation and rotation).
SamplerFilter
(Undocumented?) Enumerated type fx_sampler_filter_common from COLLADA spec.
Semantic
An Input semantic attribute. Common / defined values are pre-parsed, and the remainder are in the Other variant.
Shader
A shader element.
ShapeGeom
The geometry of a shape. This can be either an inline definition using Plane, Sphere etc, or a Instance<Geometry>, which can reference other geometry types.
SurfaceChannels
The per-texel layout of the format. The length of the enumeration string indicates how many channels there are and each letter represents the name of a channel. There are typically 1 to 4 channels.
SurfaceFace
Specifies a surface on a cube.
SurfaceInit
A Surface initialization option, which specifies whether to initialize the surface and how to do so.
SurfaceOption
Contains additional hints about data relationships and other things to help an application pick the best format.
SurfacePrecision
The precision of the texel channel value.
SurfaceRange
The range of texel channel values. Each channel represents a range of values. Some example ranges are signed or unsigned integers, or are within a clamped range such as 0.0f to 1.0f, or are a high dynamic range via floating point.
SurfaceType
Specifies a surface on a cube.
Transform
A transformation, that can be represented as a matrix (but may be expressed in another way for convenience).
UpAxis
Descriptive information about the coordinate system of the geometric data. All coordinates are right-handed by definition.
Url
A (really) basic URL parser.
WrapMode
Wrap modes that affect the interpretation of s, t, and p texture coordinates in Sampler* elements.

Traits§

ArrayKind
A trait for the common functionality of the array types.
ParseLibrary
A trait for nodes that can be placed in a library element.
ProfileData
A trait for the types that are legal to go in a TechniqueFx<T>.

Type Aliases§

LineStrips
Provides the information needed to bind vertex attributes together and then organize those vertices into connected line-strips.
Lines
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into individual lines.
NameRef
A strongly typed string referencing a T.
PolyList
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into individual polygons.
Polygons
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into individual polygons.
TriFans
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into connected triangles.
TriStrips
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into connected triangles.
Triangles
Provides the information needed for a mesh to bind vertex attributes together and then organize those vertices into individual triangles.
UrlRef
A strongly typed URL referencing a T.