API Overview — @aspose/3d for TypeScript

Пакет: @aspose/3d (v24.12.0) Мова: TypeScript / Node.js 18+ Ліцензія: MIT

@aspose/3d є бібліотекою з ліцензією MIT для читання, створення та експорту 3D‑сцен у Node.js. Вона постачається з повними визначеннями типів TypeScript, єдиною залежністю під час виконання (xmldom).


Enumerations

npm install @aspose/3d

Enumerations tsconfig.json налаштування для правильного розв’язання підшляхів:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true
  }
}

Основні класи

Enumerations

Кореневий контейнер 3D‑сцени. Увесь вміст; вузли, геометрія, матеріали та анімації; зберігаються у дереві, коренем якого є scene.rootNode.Використовуйте open() / openFromBuffer() для завантаження файлу та save() / saveToBuffer() для експорту.

EnumerationsEnumerationsEnumerations
rootNodeNodeКорінь графа сцени
assetInfoAssetInfoМетадані файлу (створювач, одиниці вимірювання, система координат)
animationClipsAnimationClip[]Усі кліпи анімації в сцені
open(path, opts?)(string, LoadOptions?) → voidЗавантажити файл з диска
openFromBuffer(buf, opts?)(Buffer, LoadOptions?) → voidЗавантажити з буфера у пам’яті
save(path, opts?)(string, SaveOptions?) → voidЗберегти на диск (формат визначається за розширенням)
saveToBuffer(ext, opts?)(string, SaveOptions?) → BufferЗберегти у буфер у пам’яті
createAnimationClip(name)(string) → AnimationClipСтворити та зареєструвати новий анімаційний кліп

Enumerations

Іменований вузол дерева у графі сцени. Вузли несуть необов’язковий Entity (mesh, camera, light) і Transform яка позиціонує вузол відносно його батька.

EnumerationsEnumerationsEnumerations
namestringНазва вузла
childNodesNode[]Прямі дочірні вузли
entity`Entitynull`
transformTransformЛокальне переміщення, обертання, масштаб
materialsMaterial[]Матеріали, призначені цьому вузлу
createChildNode(name)(string) → NodeДодати дочірній вузол
getChildNode(name)`(string) → Nodenull`

Enumerations

Полігональна сітка; основний тип геометрії. Розширює Geometry.

EnumerationsEnumerationsEnumerations
controlPointsVector4[]Позиції вершин (w=1 для позицій)
polygonCountnumberКількість полігонів
createPolygon(indices)(number[]) → voidДодати полігон (трикутник або чотирикутник)
getElement(type)`(VertexElementType) → VertexElementnull`
createElement(type)(VertexElementType) → VertexElementСтворити елемент вершини

Enumerations

Локальне перетворення, застосоване до вузла.

EnumerationsEnumerationsEnumerations
translationVector3Локальна позиція
eulerAnglesVector3Ейлерова обертання в градусах (порядок XYZ)
rotationQuaternionОбертання у вигляді кватерніону
scalingVector3Локальний масштаб

Класи матеріалів

EnumerationsEnumerationsКлючові властивості
LambertMaterialРозсіяне + навколишнє затіненняdiffuseColor, ambientColor, transparency
PhongMaterialДодає відблиск + емісивність до LambertspecularColor, shininess, emissiveColor
PbrMaterialФізично обґрунтовано для glTF 2.0albedo, metallicFactor, roughnessFactor, emissiveColor

Класи математики

EnumerationsEnumerations
Vector33-component double-precision vector (x, y, z)
Vector44-component vector for homogeneous math (x, y, z, w)
FVector3Варіант одинарної точності, що використовується у даних вершин
Matrix44×4 transformation matrix; multiply, invert, decompose
QuaternionКватерніон обертання; fromEulerAngle, toEulerAngles, slerp
BoundingBoxОсьово-узгоджений обмежувальний короб; minimum, maximum, center, size, merge

Класи анімації

EnumerationsEnumerations
AnimationClipНазваний кліп; містить AnimationNode список; доступний через scene.animationClips
AnimationNodeПрив’язує кліп до іменованого вузла сцени; містить AnimationChannel список
AnimationChannelЗосереджується на одній властивості (наприклад, переміщення X); містить KeyframeSequence
KeyframeSequenceВпорядкований список KeyFrame об’єкти з interpolation і extrapolation
KeyFrameОдинарна пара час/значення

Enumerations

EnumerationsEnumerationsEnumerations
VertexElementTypeNORMAL, UV, VERTEX_COLOR, BINORMAL, TANGENTСемантика елементу вершини
MappingModeCONTROL_POINT, POLYGON_VERTEX, POLYGON, ALL_SAMEЯк дані відображаються на геометрію
ReferenceModeDIRECT, INDEX, INDEX_TO_DIRECTСтратегія індексування даних елементу вершини
InterpolationCONSTANT, LINEAR, BEZIERІнтерполяція ключових кадрів
ExtrapolationCONSTANT, GRADIENT, CYCLE, CYCLE_RELATIVE, OSCILLATEПоведінка поза діапазоном ключових кадрів

Модулі форматів

Класи параметрів, специфічних для формату, експортуються з підмодулів. Імпортуйте їх окремо:

import { ObjLoadOptions } from '@aspose/3d/formats/obj';
import { GltfSaveOptions, GltfFormat } from '@aspose/3d/formats/gltf';
import { StlLoadOptions, StlSaveOptions } from '@aspose/3d/formats/stl';
import { FbxLoadOptions, FbxSaveOptions } from '@aspose/3d/formats/fbx';
import { ColladaLoadOptions } from '@aspose/3d/formats/collada';
import { ThreeMfSaveOptions } from '@aspose/3d/formats/3mf';

Модуль OBJ (@aspose/3d/formats/obj)

EnumerationsКлючові параметри
ObjLoadOptionsenableMaterials, flipCoordinateSystem, scale, normalizeNormal

Модуль glTF/GLB (@aspose/3d/formats/gltf)

EnumerationsКлючові параметри
GltfSaveOptionsbinaryMode (true → .glb), flipTexCoordV
GltfFormatGltfFormat.getInstance(): екземпляр формату для scene.save()

Модуль STL (@aspose/3d/formats/stl)

EnumerationsКлючові параметри
StlLoadOptionsN/A
StlSaveOptionsbinaryMode (false → ASCII, true → binary)

FBX модуль (@aspose/3d/formats/fbx)

EnumerationsКлючові параметри
FbxLoadOptionsN/A
FbxSaveOptionsembedTextures

Підтримувані формати

EnumerationsEnumerationsEnumerationsEnumerations
Enumerations.objEnumerationsEnumerations
glTF 2.0.gltfEnumerationsEnumerations
Enumerations.glbEnumerationsEnumerations
STL.stlEnumerationsEnumerations
FBX.fbxНі*Ні*
COLLADA.daeEnumerationsEnumerations
3MF.3mfEnumerationsEnumerations

Приклад швидкої довідки

import { Scene } from '@aspose/3d';
import { ObjLoadOptions } from '@aspose/3d/formats/obj';
import { GltfSaveOptions } from '@aspose/3d/formats/gltf';

// Load OBJ with materials
const scene = new Scene();
const loadOpts = new ObjLoadOptions();
loadOpts.enableMaterials = true;
scene.open('input.obj', loadOpts);

// Inspect root nodes
for (const node of scene.rootNode.childNodes) {
    console.log(`Node: ${node.name}, entity: ${node.entity?.constructor.name}`);
}

// Export as GLB (binary glTF)
const saveOpts = new GltfSaveOptions();
saveOpts.binaryMode = true;
scene.save('output.glb', saveOpts);

Див. також

 Українська