UNPKG

@gltf-transform/core

Version:

glTF 2.0 SDK for JavaScript and TypeScript, on Web and Node.js.

1,453 lines (1,452 loc) 138 kB
import { Graph, Graph as Graph$1, GraphEdge, GraphNode, LiteralKeys, Ref, RefList, RefMap, RefMap as RefMap$1, RefSet, RefSet as RefSet$1 } from "property-graph"; //#region src/constants.d.ts /** * Current version of the package. * @hidden */ declare const VERSION: string; /** * TypeScript utility for nullable types. * @hidden */ type Nullable<T> = { [P in keyof T]: T[P] | null }; /** * 2-dimensional vector. * @hidden */ type vec2 = [number, number]; /** * 3-dimensional vector. * @hidden */ type vec3 = [number, number, number]; /** * 4-dimensional vector, e.g. RGBA or a quaternion. * @hidden */ type vec4 = [number, number, number, number]; /** * 3x3 matrix, e.g. an affine transform of a 2D vector. * @hidden */ type mat3 = [number, number, number, number, number, number, number, number, number]; /** * 4x4 matrix, e.g. an affine transform of a 3D vector. * @hidden */ type mat4 = [number, number, number, number, number, number, number, number, number, number, number, number, number, number, number, number]; /** @hidden */ type bbox = { min: vec3; max: vec3; }; /** @hidden */ declare const GLB_BUFFER = "@glb.bin"; /** * Abstraction representing any one of the typed array classes supported by glTF and JavaScript. * @hidden */ type TypedArray = Float64Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Float16Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Uint16Array<ArrayBuffer> | Uint8Array<ArrayBuffer> | Int16Array<ArrayBuffer> | Int8Array<ArrayBuffer>; /** * Abstraction representing the typed array constructors supported by glTF and JavaScript. * @hidden */ type TypedArrayConstructor = Float64ArrayConstructor | Float32ArrayConstructor | Float16ArrayConstructor | Uint32ArrayConstructor | Uint16ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Int8ArrayConstructor; /** String IDs for core {@link Property} types. */ declare enum PropertyType { ACCESSOR = "Accessor", ANIMATION = "Animation", ANIMATION_CHANNEL = "AnimationChannel", ANIMATION_SAMPLER = "AnimationSampler", BUFFER = "Buffer", CAMERA = "Camera", MATERIAL = "Material", MESH = "Mesh", PRIMITIVE = "Primitive", PRIMITIVE_TARGET = "PrimitiveTarget", NODE = "Node", ROOT = "Root", SCENE = "Scene", SKIN = "Skin", TEXTURE = "Texture", TEXTURE_INFO = "TextureInfo" } /** Vertex layout method. */ declare enum VertexLayout { /** * Stores vertex attributes in a single buffer view per mesh primitive. Interleaving vertex * data may improve performance by reducing page-thrashing in GPU memory. */ INTERLEAVED = "interleaved", /** * Stores each vertex attribute in a separate buffer view. May decrease performance by causing * page-thrashing in GPU memory. Some 3D engines may prefer this layout, e.g. for simplicity. */ SEPARATE = "separate" } /** Accessor usage. */ declare enum BufferViewUsage { ARRAY_BUFFER = "ARRAY_BUFFER", ELEMENT_ARRAY_BUFFER = "ELEMENT_ARRAY_BUFFER", INVERSE_BIND_MATRICES = "INVERSE_BIND_MATRICES", OTHER = "OTHER", SPARSE = "SPARSE" } /** Texture channels. */ declare enum TextureChannel { R = 4096, G = 256, B = 16, A = 1 } declare enum Format { GLTF = "GLTF", GLB = "GLB" } declare const ComponentTypeToTypedArray: Record<string, TypedArrayConstructor>; //#endregion //#region src/types/gltf.d.ts /** * Module for glTF 2.0 Interface */ declare namespace GLTF { /** Data type of the values composing each element in the accessor. */ type AccessorComponentType = 5120 | 5121 | 5122 | 5123 | 5125 | 5126 | 5130 | 5131; /** Element type contained by the accessor (SCALAR, VEC2, ...). */ type AccessorType = 'SCALAR' | 'VEC2' | 'VEC3' | 'VEC4' | 'MAT2' | 'MAT3' | 'MAT4'; /** Name of the property to be modified by an animation channel. */ type AnimationChannelTargetPath = 'translation' | 'rotation' | 'scale' | 'weights'; /** Interpolation method. */ type AnimationSamplerInterpolation = 'LINEAR' | 'STEP' | 'CUBICSPLINE'; /** Projection type used by a camera. */ type CameraType = 'perspective' | 'orthographic'; /** The alpha rendering mode of the material. */ type MaterialAlphaMode = 'OPAQUE' | 'MASK' | 'BLEND'; /** The type of the GL primitives to render. */ type MeshPrimitiveMode = 0 | 1 | 2 | 3 | 4 | 5 | 6; /** Magnification filter. Values match to WebGL enums: 9728 (NEAREST) and 9729 (LINEAR). */ type TextureMagFilter = 9728 | 9729; /** Minification filter. All valid values correspond to WebGL enums. */ type TextureMinFilter = 9728 | 9729 | 9984 | 9985 | 9986 | 9987; /** S (U) wrapping mode. All valid values correspond to WebGL enums. */ type TextureWrapMode = 33071 | 33648 | 10497; /** * glTF Property */ interface IProperty { /** * Dictionary object with extension-specific objects */ extensions?: Record<string, unknown>; /** * Application-Specific data */ extras?: Record<string, unknown>; } /** * glTF Child of Root Property */ interface IChildRootProperty extends IProperty { /** * The user-defined name of this object */ name?: string; } /** * Indices of those attributes that deviate from their initialization value */ interface IAccessorSparseIndices extends IProperty { /** * The index of the bufferView with sparse indices. Referenced bufferView can't have * ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target */ bufferView: number; /** * The offset relative to the start of the bufferView in bytes. Must be aligned */ byteOffset?: number; /** * The indices data type. Valid values correspond to WebGL enums: 5121 (UNSIGNED_BYTE), * 5123 (UNSIGNED_SHORT), 5125 (UNSIGNED_INT) */ componentType: AccessorComponentType; } /** * Array of size accessor.sparse.count times number of components storing the displaced accessor * attributes pointed by accessor.sparse.indices */ interface IAccessorSparseValues extends IProperty { /** * The index of the bufferView with sparse values. Referenced bufferView can't have * ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER target */ bufferView: number; /** * The offset relative to the start of the bufferView in bytes. Must be aligned */ byteOffset?: number; } /** * Sparse storage of attributes that deviate from their initialization value */ interface IAccessorSparse extends IProperty { /** * The number of attributes encoded in this sparse accessor */ count: number; /** * Index array of size count that points to those accessor attributes that deviate from * their initialization value. Indices must strictly increase */ indices: IAccessorSparseIndices; /** * Array of size count times number of components, storing the displaced accessor attributes * pointed by indices. Substituted values must have the same componentType and number of * components as the base accessor */ values: IAccessorSparseValues; } /** * A typed view into a bufferView. A bufferView contains raw binary data. An accessor provides * a typed view into a bufferView or a subset of a bufferView similar to how WebGL's * vertexAttribPointer() defines an attribute in a buffer */ interface IAccessor extends IChildRootProperty { /** * The index of the bufferview */ bufferView?: number; /** * The offset relative to the start of the bufferView in bytes */ byteOffset?: number; /** * The datatype of components in the attribute */ componentType: AccessorComponentType; /** * Specifies whether integer data values should be normalized */ normalized?: boolean; /** * The number of attributes referenced by this accessor */ count: number; /** * Specifies if the attribute is a scalar, vector, or matrix */ type: AccessorType; /** * Maximum value of each component in this attribute */ max?: number[]; /** * Minimum value of each component in this attribute */ min?: number[]; /** * Sparse storage of attributes that deviate from their initialization value */ sparse?: IAccessorSparse; } /** * Targets an animation's sampler at a node's property */ interface IAnimationChannel extends IProperty { /** * The index of a sampler in this animation used to compute the value for the target */ sampler: number; /** * The index of the node and TRS property to target */ target: IAnimationChannelTarget; } /** * The index of the node and TRS property that an animation channel targets */ interface IAnimationChannelTarget extends IProperty { /** * The index of the node to target, when undefined, the animated object MAY be defined by an extension. */ node?: number; /** * The name of the node's TRS property to modify, or the weights of the Morph Targets it * instantiates */ path: AnimationChannelTargetPath; } /** * Combines input and output accessors with an interpolation algorithm to define a keyframe * graph (but not its target) */ interface IAnimationSampler extends IProperty { /** * The index of an accessor containing keyframe input values, e.g., time */ input: number; /** * Interpolation algorithm */ interpolation?: AnimationSamplerInterpolation; /** * The index of an accessor, containing keyframe output values */ output: number; } /** * A keyframe animation */ interface IAnimation extends IChildRootProperty { /** * An array of channels, each of which targets an animation's sampler at a node's property */ channels: IAnimationChannel[]; /** * An array of samplers that combines input and output accessors with an interpolation * algorithm to define a keyframe graph (but not its target) */ samplers: IAnimationSampler[]; } /** * Metadata about the glTF asset */ interface IAsset extends IChildRootProperty { /** * A copyright message suitable for display to credit the content creator */ copyright?: string; /** * Tool that generated this glTF model. Useful for debugging */ generator?: string; /** * The glTF version that this asset targets */ version: string; /** * The minimum glTF version that this asset targets */ minVersion?: string; } /** * A buffer points to binary geometry, animation, or skins */ interface IBuffer extends IChildRootProperty { /** * The uri of the buffer. Relative paths are relative to the .gltf file. Instead of * referencing an external file, the uri can also be a data-uri */ uri?: string; /** * The length of the buffer in bytes */ byteLength: number; } /** * A view into a buffer generally representing a subset of the buffer */ interface IBufferView extends IChildRootProperty { /** * The index of the buffer */ buffer: number; /** * The offset into the buffer in bytes */ byteOffset?: number; /** * The length of the bufferView in bytes */ byteLength: number; /** * The stride, in bytes */ byteStride?: number; /** * The target that the GPU buffer should be bound to */ target?: number; } /** * An orthographic camera containing properties to create an orthographic projection matrix */ interface ICameraOrthographic extends IProperty { /** * The floating-point horizontal magnification of the view. Must not be zero */ xmag: number; /** * The floating-point vertical magnification of the view. Must not be zero */ ymag: number; /** * The floating-point distance to the far clipping plane. zfar must be greater than znear */ zfar: number; /** * The floating-point distance to the near clipping plane */ znear: number; } /** * A perspective camera containing properties to create a perspective projection matrix */ interface ICameraPerspective extends IProperty { /** * The floating-point aspect ratio of the field of view */ aspectRatio?: number; /** * The floating-point vertical field of view in radians */ yfov: number; /** * The floating-point distance to the far clipping plane */ zfar?: number; /** * The floating-point distance to the near clipping plane */ znear: number; } /** * A camera's projection. A node can reference a camera to apply a transform to place the * camera in the scene */ interface ICamera extends IChildRootProperty { /** * An orthographic camera containing properties to create an orthographic projection matrix */ orthographic?: ICameraOrthographic; /** * A perspective camera containing properties to create a perspective projection matrix */ perspective?: ICameraPerspective; /** * Specifies if the camera uses a perspective or orthographic projection */ type: CameraType; } /** * Image data used to create a texture. Image can be referenced by URI or bufferView index. * mimeType is required in the latter case */ interface IImage extends IChildRootProperty { /** * The uri of the image. Relative paths are relative to the .gltf file. Instead of * referencing an external file, the uri can also be a data-uri. The image format must be * jpg or png */ uri?: string; /** * The image's MIME type */ mimeType?: string; /** * The index of the bufferView that contains the image. Use this instead of the image's uri * property */ bufferView?: number; } /** * Material Normal Texture Info */ interface IMaterialNormalTextureInfo extends ITextureInfo { /** * The scalar multiplier applied to each normal vector of the normal texture */ scale?: number; } /** * Material Occlusion Texture Info */ interface IMaterialOcclusionTextureInfo extends ITextureInfo { /** * A scalar multiplier controlling the amount of occlusion applied */ strength?: number; } /** * A set of parameter values that are used to define the metallic-roughness material model from * Physically-Based Rendering (PBR) methodology */ interface IMaterialPbrMetallicRoughness { /** * The material's base color factor */ baseColorFactor?: number[]; /** * The base color texture */ baseColorTexture?: ITextureInfo; /** * The metalness of the material */ metallicFactor?: number; /** * The roughness of the material */ roughnessFactor?: number; /** * The metallic-roughness texture */ metallicRoughnessTexture?: ITextureInfo; } /** * The material appearance of a primitive */ interface IMaterial extends IChildRootProperty { /** * A set of parameter values that are used to define the metallic-roughness material model * from Physically-Based Rendering (PBR) methodology. When not specified, all the default * values of pbrMetallicRoughness apply */ pbrMetallicRoughness?: IMaterialPbrMetallicRoughness; /** * The normal map texture */ normalTexture?: IMaterialNormalTextureInfo; /** * The occlusion map texture */ occlusionTexture?: IMaterialOcclusionTextureInfo; /** * The emissive map texture */ emissiveTexture?: ITextureInfo; /** * The RGB components of the emissive color of the material. These values are linear. If * an emissiveTexture is specified, this value is multiplied with the texel values */ emissiveFactor?: number[]; /** * The alpha rendering mode of the material */ alphaMode?: MaterialAlphaMode; /** * The alpha cutoff value of the material */ alphaCutoff?: number; /** * Specifies whether the material is double sided */ doubleSided?: boolean; } /** * Geometry to be rendered with the given material */ interface IMeshPrimitive extends IProperty { /** * A dictionary object, where each key corresponds to mesh attribute semantic and each * value is the index of the accessor containing attribute's data */ attributes: { [name: string]: number; }; /** * The index of the accessor that contains the indices */ indices?: number; /** * The index of the material to apply to this primitive when rendering */ material?: number; /** * The type of primitives to render. All valid values correspond to WebGL enums */ mode?: MeshPrimitiveMode; /** * An array of Morph Targets, each Morph Target is a dictionary mapping attributes (only * POSITION, NORMAL, and TANGENT supported) to their deviations in the Morph Target */ targets?: { [name: string]: number; }[]; } /** * A set of primitives to be rendered. A node can contain one mesh. A node's transform * places the mesh in the scene */ interface IMesh extends IChildRootProperty { /** * An array of primitives, each defining geometry to be rendered with a material */ primitives: IMeshPrimitive[]; /** * Array of weights to be applied to the Morph Targets */ weights?: number[]; } /** * A node in the node hierarchy */ interface INode extends IChildRootProperty { /** * The index of the camera referenced by this node */ camera?: number; /** * The indices of this node's children */ children?: number[]; /** * The index of the skin referenced by this node */ skin?: number; /** * A floating-point 4x4 transformation matrix stored in column-major order */ matrix?: number[]; /** * The index of the mesh in this node */ mesh?: number; /** * The node's unit quaternion rotation in the order (x, y, z, w), where w is the scalar */ rotation?: number[]; /** * The node's non-uniform scale, given as the scaling factors along the x, y, and z axes */ scale?: number[]; /** * The node's translation along the x, y, and z axes */ translation?: number[]; /** * The weights of the instantiated Morph Target. Number of elements must match number of * Morph Targets of used mesh */ weights?: number[]; } /** * Texture sampler properties for filtering and wrapping modes */ interface ISampler extends IChildRootProperty { /** * Magnification filter. Valid values correspond to WebGL enums: 9728 (NEAREST) and 9729 * (LINEAR) */ magFilter?: TextureMagFilter; /** * Minification filter. All valid values correspond to WebGL enums */ minFilter?: TextureMinFilter; /** * S (U) wrapping mode. All valid values correspond to WebGL enums */ wrapS?: TextureWrapMode; /** * T (V) wrapping mode. All valid values correspond to WebGL enums */ wrapT?: TextureWrapMode; } /** * The root nodes of a scene */ interface IScene extends IChildRootProperty { /** * The indices of each root node */ nodes: number[]; } /** * Joints and matrices defining a skin */ interface ISkin extends IChildRootProperty { /** * The index of the accessor containing the floating-point 4x4 inverse-bind matrices. The * default is that each matrix is a 4x4 identity matrix, which implies that inverse-bind * matrices were pre-applied */ inverseBindMatrices?: number; /** * The index of the node used as a skeleton root. When undefined, joints transforms resolve * to scene root */ skeleton?: number; /** * Indices of skeleton nodes, used as joints in this skin. The array length must be the * same as the count property of the inverseBindMatrices accessor (when defined) */ joints: number[]; } /** * A texture and its sampler */ interface ITexture extends IChildRootProperty { /** * The index of the sampler used by this texture. When undefined, a sampler with repeat * wrapping and auto filtering should be used */ sampler?: number; /** * The index of the image used by this texture */ source?: number; } /** * Reference to a texture */ interface ITextureInfo extends IProperty { /** * The index of the texture */ index: number; /** * The set index of texture's TEXCOORD attribute used for texture coordinate mapping */ texCoord?: number; } /** * The root object for a glTF asset */ interface IGLTF extends IProperty { /** * An array of accessors. An accessor is a typed view into a bufferView */ accessors?: IAccessor[]; /** * An array of keyframe animations */ animations?: IAnimation[]; /** * Metadata about the glTF asset */ asset: IAsset; /** * An array of buffers. A buffer points to binary geometry, animation, or skins */ buffers?: IBuffer[]; /** * An array of bufferViews. A bufferView is a view into a buffer generally representing * a subset of the buffer */ bufferViews?: IBufferView[]; /** * An array of cameras */ cameras?: ICamera[]; /** * Names of glTF extensions used somewhere in this asset */ extensionsUsed?: string[]; /** * Names of glTF extensions required to properly load this asset */ extensionsRequired?: string[]; /** * An array of images. An image defines data used to create a texture */ images?: IImage[]; /** * An array of materials. A material defines the appearance of a primitive */ materials?: IMaterial[]; /** * An array of meshes. A mesh is a set of primitives to be rendered */ meshes?: IMesh[]; /** * An array of nodes */ nodes?: INode[]; /** * An array of samplers. A sampler contains properties for texture filtering and wrapping * modes */ samplers?: ISampler[]; /** * The index of the default scene */ scene?: number; /** * An array of scenes */ scenes?: IScene[]; /** * An array of skins. A skin is defined by joints and matrices */ skins?: ISkin[]; /** * An array of textures */ textures?: ITexture[]; } } //#endregion //#region src/json-document.d.ts /** * *Raw glTF asset, with its JSON and binary resources.* * * A JSONDocument is a plain object containing the raw JSON of a glTF file, and any binary or image * resources referenced by that file. When modifying the file, it should generally be first * converted to the more useful {@link Document} wrapper. * * When loading glTF data that is in memory, or which the I/O utilities cannot otherwise access, * you might assemble the JSONDocument yourself, then convert it to a Document with * {@link PlatformIO.readJSON}(jsonDocument). * * Usage: * * ```ts * import fs from 'fs/promises'; * * const jsonDocument = { * // glTF JSON schema. * json: { * asset: {version: '2.0'}, * images: [{uri: 'image1.png'}, {uri: 'image2.png'}] * }, * * // URI → Uint8Array mapping. * resources: { * 'image1.png': await fs.readFile('image1.png'), * 'image2.png': await fs.readFile('image2.png'), * } * }; * * const document = await new NodeIO().readJSON(jsonDocument); * ``` * * @category Documents */ interface JSONDocument { json: GLTF.IGLTF; resources: { [s: string]: Uint8Array<ArrayBuffer>; }; } //#endregion //#region src/utils/buffer-utils.d.ts /** * *Common utilities for working with Uint8Array and Buffer objects.* * * @category Utilities */ declare class BufferUtils { /** Creates a byte array from a Data URI. */ static createBufferFromDataURI(dataURI: string): Uint8Array<ArrayBuffer>; /** Encodes text to a byte array. */ static encodeText(text: string): Uint8Array; /** Decodes a byte array to text. */ static decodeText(array: Uint8Array): string; /** * Concatenates N byte arrays. */ static concat(arrays: Uint8Array[]): Uint8Array<ArrayBuffer>; /** * Pads a Uint8Array to the next 4-byte boundary. * * Reference: [glTF → Data Alignment](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment) */ static pad(srcArray: Uint8Array, paddingByte?: number): Uint8Array; /** Pads a number to 4-byte boundaries. */ static padNumber(v: number): number; /** Returns true if given byte array instances are equal. */ static equals(a: Uint8Array, b: Uint8Array): boolean; /** * Returns a Uint8Array view of a typed array, with the same underlying ArrayBuffer. * * A shorthand for: * * ```js * const buffer = new Uint8Array( * array.buffer, * array.byteOffset + byteOffset, * Math.min(array.byteLength, byteLength) * ); * ``` * */ static toView(a: TypedArray, byteOffset?: number, byteLength?: number): Uint8Array<ArrayBuffer>; static assertView(view: Uint8Array): Uint8Array<ArrayBuffer>; static assertView(view: Uint8Array | null): Uint8Array<ArrayBuffer> | null; } //#endregion //#region src/utils/color-utils.d.ts /** * *Common utilities for working with colors in vec3, vec4, or hexadecimal form.* * * Provides methods to convert linear components (vec3, vec4) to sRGB hex values. All colors in * the glTF specification, excluding color textures, are linear. Hexadecimal values, in sRGB * colorspace, are accessible through helper functions in the API as a convenience. * * ```typescript * // Hex (sRGB) to factor (linear). * const factor = ColorUtils.hexToFactor(0xFFCCCC, []); * * // Factor (linear) to hex (sRGB). * const hex = ColorUtils.factorToHex([1, .25, .25]) * ``` * * @category Utilities */ declare class ColorUtils { /** * Converts sRGB hexadecimal to linear components. * @typeParam T vec3 or vec4 linear components. */ static hexToFactor<T = vec3 | vec4>(hex: number, target: T): T; /** * Converts linear components to sRGB hexadecimal. * @typeParam T vec3 or vec4 linear components. */ static factorToHex<T = vec3 | vec4>(factor: T): number; /** * Converts sRGB components to linear components. * @typeParam T vec3 or vec4 linear components. */ static convertSRGBToLinear<T = vec3 | vec4>(source: T, target: T): T; /** * Converts linear components to sRGB components. * @typeParam T vec3 or vec4 linear components. */ static convertLinearToSRGB<T = vec3 | vec4>(source: T, target: T): T; } //#endregion //#region src/utils/file-utils.d.ts /** * *Utility class for working with file systems and URI paths.* * * @category Utilities */ declare class FileUtils { /** * Extracts the basename from a file path, e.g. "folder/model.glb" -> "model". * See: {@link HTTPUtils.basename} */ static basename(uri: string): string; /** * Extracts the extension from a file path, e.g. "folder/model.glb" -> "glb". * See: {@link HTTPUtils.extension} */ static extension(uri: string): string; } //#endregion //#region src/properties/property.d.ts type PropertyResolver<T extends Property> = (p: T) => T; declare const COPY_IDENTITY: <T extends Property>(t: T) => T; interface IProperty$1 { name: string; extras: Record<string, unknown>; } /** * *Properties represent distinct resources in a glTF asset, referenced by other properties.* * * For example, each material and texture is a property, with material properties holding * references to the textures. All properties are created with factory methods on the * {@link Document} in which they should be constructed. Properties are destroyed by calling * {@link Property.dispose}(). * * Usage: * * ```ts * const texture = doc.createTexture('myTexture'); * doc.listTextures(); // → [texture x 1] * * // Attach a texture to a material. * material.setBaseColorTexture(texture); * material.getBaseColortexture(); // → texture * * // Detaching a texture removes any references to it, except from the doc. * texture.detach(); * material.getBaseColorTexture(); // → null * doc.listTextures(); // → [texture x 1] * * // Disposing a texture removes all references to it, and its own references. * texture.dispose(); * doc.listTextures(); // → [] * ``` * * Reference: * - [glTF → Concepts](https://github.com/KhronosGroup/gltf/blob/main/specification/2.0/README.md#concepts) * * @category Properties */ declare abstract class Property<T extends IProperty$1 = IProperty$1> extends GraphNode<T> { /** Property type. */ abstract readonly propertyType: string; /** * Internal graph used to search and maintain references. * @override * @hidden */ protected readonly graph: Graph$1<Property>; /** @hidden */ constructor(graph: Graph$1<Property>, name?: string); /** * Initializes instance data for a subclass. Because subclass constructors run after the * constructor of the parent class, and 'create' events dispatched by the parent class * assume the instance is fully initialized, it's best to do any initialization here. * @hidden */ protected abstract init(): void; /** * Returns the Graph associated with this Property. For internal use. * @hidden * @experimental */ getGraph(): Graph$1<Property>; /** * Returns default attributes for the property. Empty lists and maps should be initialized * to empty arrays and objects. Always invoke `super.getDefaults()` and extend the result. */ protected getDefaults(): Nullable<T>; /** @hidden */ protected set<K extends LiteralKeys<T>>(attribute: K, value: T[K]): this; /********************************************************************************************** * Name. */ /** * Returns the name of this property. While names are not required to be unique, this is * encouraged, and non-unique names will be overwritten in some tools. For custom data about * a property, prefer to use Extras. */ getName(): string; /** * Sets the name of this property. While names are not required to be unique, this is * encouraged, and non-unique names will be overwritten in some tools. For custom data about * a property, prefer to use Extras. */ setName(name: string): this; /********************************************************************************************** * Extras. */ /** * Returns a reference to the Extras object, containing application-specific data for this * Property. Extras should be an Object, not a primitive value, for best portability. */ getExtras(): Record<string, unknown>; /** * Updates the Extras object, containing application-specific data for this Property. Extras * should be an Object, not a primitive value, for best portability. */ setExtras(extras: Record<string, unknown>): this; /********************************************************************************************** * Graph state. */ /** * Makes a copy of this property, with the same resources (by reference) as the original. */ clone(): this; /** * Copies all data from another property to this one. Child properties are copied by reference, * unless a 'resolve' function is given to override that. * @param other Property to copy references from. * @param resolve Function to resolve each Property being transferred. Default is identity. */ copy(other: this, resolve?: PropertyResolver<Property>): this; /** * Returns true if two properties are deeply equivalent, recursively comparing the attributes * of the properties. Optionally, a 'skip' set may be included, specifying attributes whose * values should not be considered in the comparison. * * Example: Two {@link Primitive Primitives} are equivalent if they have accessors and * materials with equivalent content — but not necessarily the same specific accessors * and materials. */ equals(other: this, skip?: Set<string>): boolean; detach(): this; /** * Returns a list of all properties that hold a reference to this property. For example, a * material may hold references to various textures, but a texture does not hold references * to the materials that use it. * * It is often necessary to filter the results for a particular type: some resources, like * {@link Accessor}s, may be referenced by different types of properties. Most properties * include the {@link Root} as a parent, which is usually not of interest. * * Usage: * * ```ts * const materials = texture * .listParents() * .filter((p) => p instanceof Material) * ``` */ listParents(): Property[]; } //#endregion //#region src/properties/extension-property.d.ts /** * *Base class for all {@link Property} types that can be attached by an {@link Extension}.* * * After an {@link Extension} is attached to a glTF {@link Document}, the Extension may be used to * construct ExtensionProperty instances, to be referenced throughout the document as prescribed by * the Extension. For example, the `KHR_materials_clearcoat` Extension defines a `Clearcoat` * ExtensionProperty, which is referenced by {@link Material} Properties in the Document, and may * contain references to {@link Texture} properties of its own. * * For more information on available extensions and their usage, see [Extensions](/extensions). * * Reference: * - [glTF → Extensions](https://github.com/KhronosGroup/gltf/blob/main/specification/2.0/README.md#specifying-extensions) * * @category Properties */ declare abstract class ExtensionProperty<T extends IProperty$1 = IProperty$1> extends Property<T> { static EXTENSION_NAME: string; abstract readonly extensionName: string; /** List of supported {@link Property} types. */ abstract readonly parentTypes: string[]; /** @hidden */ _validateParent(parent: ExtensibleProperty): void; } //#endregion //#region src/properties/extensible-property.d.ts interface IExtensibleProperty extends IProperty$1 { extensions: RefMap$1<ExtensionProperty>; } /** * *A {@link Property} that can have {@link ExtensionProperty} instances attached.* * * Most properties are extensible. See the {@link Extension} documentation for information about * how to use extensions. * * @category Properties */ declare abstract class ExtensibleProperty<T extends IExtensibleProperty = IExtensibleProperty> extends Property<T> { protected getDefaults(): Nullable<T>; /** Returns an {@link ExtensionProperty} attached to this Property, if any. */ getExtension<Prop extends ExtensionProperty>(name: string): Prop | null; /** * Attaches the given {@link ExtensionProperty} to this Property. For a given extension, only * one ExtensionProperty may be attached to any one Property at a time. */ setExtension<Prop extends ExtensionProperty>(name: string, extensionProperty: Prop | null): this; /** Lists all {@link ExtensionProperty} instances attached to this Property. */ listExtensions(): ExtensionProperty[]; } //#endregion //#region src/properties/buffer.d.ts interface IBuffer$1 extends IExtensibleProperty { uri: string; } /** * *Buffers are low-level storage units for binary data.* * * glTF 2.0 has three concepts relevant to binary storage: accessors, buffer views, and buffers. * In glTF Transform, an {@link Accessor} is referenced by any property that requires numeric typed * array data. Meshes, Primitives, and Animations all reference Accessors. Buffers define how that * data is organized into transmitted file(s). A `.glb` file has only a single Buffer, and when * exporting to `.glb` your resources should be grouped accordingly. A `.gltf` file may reference * one or more `.bin` files — each `.bin` is a Buffer — and grouping Accessors under different * Buffers allow you to specify that structure. * * For engines that can dynamically load portions of a glTF file, splitting data into separate * buffers can allow you to avoid loading data until it is needed. For example, you might put * binary data for specific meshes into a different `.bin` buffer, or put each animation's binary * payload into its own `.bin`. * * Buffer Views define how Accessors are organized within a given Buffer. glTF Transform creates an * efficient Buffer View layout automatically at export: there is no Buffer View property exposed * by the glTF Transform API, simplifying data management. * * Usage: * * ```ts * // Create two buffers with custom filenames. * const buffer1 = doc.createBuffer('buffer1') * .setURI('part1.bin'); * const buffer2 = doc.createBuffer('buffer2') * .setURI('part2.bin'); * * // Assign the attributes of two meshes to different buffers. If the meshes * // had indices or morph target attributes, you would also want to relocate * // those accessors. * mesh1 * .listPrimitives() * .forEach((primitive) => primitive.listAttributes() * .forEach((attribute) => attribute.setBuffer(buffer1))); * mesh2 * .listPrimitives() * .forEach((primitive) => primitive.listAttributes() * .forEach((attribute) => attribute.setBuffer(buffer2))); * * // Write to disk. Each mesh's binary data will be in a separate binary file; * // any remaining accessors will be in a third (default) buffer. * await new NodeIO().write('scene.gltf', doc); * // → scene.gltf, part1.bin, part2.bin * ``` * * References: * - [glTF → Buffers and Buffer Views](https://github.com/KhronosGroup/gltf/blob/main/specification/2.0/README.md#buffers-and-buffer-views) * - [glTF → Accessors](https://github.com/KhronosGroup/gltf/blob/main/specification/2.0/README.md#accessors) * * @category Properties */ declare class Buffer extends ExtensibleProperty<IBuffer$1> { propertyType: PropertyType.BUFFER; protected init(): void; protected getDefaults(): Nullable<IBuffer$1>; /** * Returns the URI (or filename) of this buffer (e.g. 'myBuffer.bin'). URIs are strongly * encouraged to be relative paths, rather than absolute. Use of a protocol (like `file://`) * is possible for custom applications, but will limit the compatibility of the asset with most * tools. * * Buffers commonly use the extension `.bin`, though this is not required. */ getURI(): string; /** * Sets the URI (or filename) of this buffer (e.g. 'myBuffer.bin'). URIs are strongly * encouraged to be relative paths, rather than absolute. Use of a protocol (like `file://`) * is possible for custom applications, but will limit the compatibility of the asset with most * tools. * * Buffers commonly use the extension `.bin`, though this is not required. */ setURI(uri: string): this; } //#endregion //#region src/properties/accessor.d.ts interface IAccessor$1 extends IExtensibleProperty { array: TypedArray | null; type: GLTF.AccessorType; componentType: GLTF.AccessorComponentType; normalized: boolean; sparse: boolean; buffer: Buffer; } /** * *Accessors store lists of numeric, vector, or matrix elements in a typed array.* * * All large data for {@link Mesh}, {@link Skin}, and {@link Animation} properties is stored in * {@link Accessor}s, organized into one or more {@link Buffer}s. Each accessor provides data in * typed arrays, with two abstractions: * * *Elements* are the logical divisions of the data into useful types: `"SCALAR"`, `"VEC2"`, * `"VEC3"`, `"VEC4"`, `"MAT3"`, or `"MAT4"`. The element type can be determined with the * {@link Accessor.getType getType}() method, and the number of elements in the accessor determine its * {@link Accessor.getCount getCount}(). The number of components in an element — e.g. 9 for `"MAT3"` — are its * {@link Accessor.getElementSize getElementSize}(). See {@link Accessor.Type}. * * *Components* are the numeric values within an element — e.g. `.x` and `.y` for `"VEC2"`. Various * component types are available: `BYTE`, `UNSIGNED_BYTE`, `SHORT`, `UNSIGNED_SHORT`, * `UNSIGNED_INT`, and `FLOAT`. The component type can be determined with the * {@link Accessor.getComponentType getComponentType} method, and the number of bytes in each component determine its * {@link Accessor.getComponentSize getComponentSize}. See {@link Accessor.ComponentType}. * * Usage: * * ```typescript * const accessor = doc.createAccessor('myData') * .setArray(new Float32Array([1,2,3,4,5,6,7,8,9,10,11,12])) * .setType(Accessor.Type.VEC3) * .setBuffer(doc.getRoot().listBuffers()[0]); * * accessor.getCount(); // → 4 * accessor.getElementSize(); // → 3 * accessor.getByteLength(); // → 48 * accessor.getElement(1, []); // → [4, 5, 6] * * accessor.setElement(0, [10, 20, 30]); * ``` * * Data access through the {@link Accessor.getElement getElement} and {@link Accessor.setElement setElement} * methods reads or overwrites the content of the underlying typed array. These methods use * element arrays intended to be compatible with the [gl-matrix](https://github.com/toji/gl-matrix) * library, or with the `toArray`/`fromArray` methods of libraries like three.js and babylon.js. * * Each Accessor must be assigned to a {@link Buffer}, which determines where the accessor's data * is stored in the final file. Assigning Accessors to different Buffers allows the data to be * written to different `.bin` files. * * glTF Transform does not expose many details of sparse, normalized, or interleaved accessors * through its API. It reads files using those techniques, presents a simplified view of the data * for editing, and attempts to write data back out with optimizations. For example, vertex * attributes will typically be interleaved by default, regardless of the input file. * * References: * - [glTF → Accessors](https://github.com/KhronosGroup/gltf/blob/main/specification/2.0/README.md#accessors) * * @category Properties */ declare class Accessor extends ExtensibleProperty<IAccessor$1> { propertyType: PropertyType.ACCESSOR; /********************************************************************************************** * Constants. */ /** Element type contained by the accessor (SCALAR, VEC2, ...). */ static Type: Record<string, GLTF.AccessorType>; /** Data type of the values composing each element in the accessor. */ static ComponentType: Record<string, GLTF.AccessorComponentType>; /********************************************************************************************** * Instance. */ protected init(): void; protected getDefaults(): Nullable<IAccessor$1>; /********************************************************************************************** * Static. */ /** Returns size of a given element type, in components. */ static getElementSize(type: GLTF.AccessorType): number; /** Returns size of a given component type, in bytes. */ static getComponentSize(componentType: GLTF.AccessorComponentType): number; /********************************************************************************************** * Min/max bounds. */ /** * Minimum value of each component in this attribute. Unlike in a final glTF file, values * returned by this method will reflect the minimum accounting for {@link .normalized} * state. */ getMinNormalized(target: number[]): number[]; /** * Minimum value of each component in this attribute. Values returned by this method do not * reflect normalization: use {@link .getMinNormalized} in that case. */ getMin(target: number[]): number[]; /** * Maximum value of each component in this attribute. Unlike in a final glTF file, values * returned by this method will reflect the minimum accounting for {@link .normalized} * state. */ getMaxNormalized(target: number[]): number[]; /** * Maximum value of each component in this attribute. Values returned by this method do not * reflect normalization: use {@link .getMinNormalized} in that case. */ getMax(target: number[]): number[]; /********************************************************************************************** * Layout. */ /** * Number of elements in the accessor. An array of length 30, containing 10 `VEC3` elements, * will have a count of 10. */ getCount(): number; /** Type of element stored in the accessor. `VEC2`, `VEC3`, etc. */ getType(): GLTF.AccessorType; /** * Sets type of element stored in the accessor. `VEC2`, `VEC3`, etc. Array length must be a * multiple of the component size (`VEC2` = 2, `VEC3` = 3, ...) for the selected type. */ setType(type: GLTF.AccessorType): Accessor; /** * Number of components in each element of the accessor. For example, the element size of a * `VEC2` accessor is 2. This value is determined automatically based on array length and * accessor type, specified with {@link Accessor.setType setType()}. */ getElementSize(): number; /** * Size of each component (a value in the raw array), in bytes. For example, the * `componentSize` of data backed by a `float32` array is 4 bytes. */ getComponentSize(): number; /** * Component type (float32, uint16, etc.). This value is determined automatically, and can only * be modified by replacing the underlying array. */ getComponentType(): GLTF.AccessorComponentType; /********************************************************************************************** * Normalization. */ /** * Specifies whether integer data values should be normalized (true) to [0, 1] (for unsigned * types) or [-1, 1] (for signed types), or converted directly (false) when they are accessed. * This property is defined only for accessors that contain vertex attributes or animation * output data. */ getNormalized(): boolean; /** * Specifies whether integer data values should be normalized (true) to [0, 1] (for unsigned * types) or [-1, 1] (for signed types), or converted directly (false) when they are accessed. * This property is defined only for accessors that contain vertex attributes or animation * output data. */ setNormalized(normalized: boolean): this; /********************************************************************************************** * Data access. */ /** * Returns the scalar element value at the given index. For * {@link Accessor.getNormalized normalized} integer accessors, values are * decoded and returned in floating-point form. */ getScalar(index: number): number; /** * Assigns the scalar element value at the given index. For * {@link Accessor.getNormalized normalized} integer accessors, "value" should be * given in floating-point form — it will be integer-encoded before writing * to the underlying array. */ setScalar(index: number, x: number): this; /** * Returns the vector or matrix element value at the given index. For * {@link Accessor.getNormalized normalized} integer accessors, values are * decoded and returned in floating-point form. * * Example: * * ```javascript * import { add } from 'gl-matrix/add'; * * const element = []; * const offset = [1, 1, 1]; * * for (let i = 0; i < accessor.getCount(); i++) { * accessor.getElement(i, element); * add(element, element, offset); * accessor.setElement(i, element); * } * ``` */ getElement<T extends number[]>(index: number, target: T): T; /** * Assigns the vector or matrix element value at the given index. For * {@link Accessor.getNormalized normalized} integer accessors, "value" should be * given in floating-point form — it will be integer-encoded before writing * to the underlying array. * * Example: * * ```javascript * import { add } from 'gl-matrix/add'; * * const element = []; * const offset = [1, 1, 1]; * * for (let i = 0; i < accessor.getCount(); i++) { * accessor.getElement(i, element); * add(element, element, offset); * accessor.setElement(i, element); * } * ``` */ setElement(index: number, value: number[]): this; /********************************************************************************************** * Raw data storage. */ /** * Specifies whether the accessor should be stored sparsely. When written to a glTF file, sparse * accessors store only values that differ from base values. When loaded in glTF Transform (or most * runtimes) a sparse accessor can be treated like any other accessor. Currently, glTF Transform always * uses zeroes for the base values when writing files. * @experimental */ getSparse(): boolean; /** * Specifies whether the accessor should be stored sparsely. When written to a glTF file, sparse * accessors store only values that differ from base values. When loaded in glTF Transform (or most * runtimes) a sparse accessor can be treated like any other accessor. Currently, glTF Transform always * uses zeroes for the base values when writing files. * @experimental */ setSparse(sparse: boolean): this; /** Returns the {@link Buffer} into which this accessor will be organized. */ getBuffer(): Buffer | null; /** Assigns the {@link Buffer} into which this accessor will be organized. */ setBuffer(buffer: Buffer | null): this; /** Returns the raw typed array underlying this accessor. */ getArray(): TypedArray | null; /** Assigns the raw typed array underlying this accessor. */ setArray(array: TypedArray | null): this; /** Returns the total bytelength of this accessor, exclusive of padding. */ getByteLength(): number; } //#endregion //#region src/properties/animation-sampler.d.ts interface IAnimationSampler$1 ext