TypeScript에서 glTF/GLB로 3D 장면을 수출하는 방법
Aspose.3D FOSS는 GLTF 2.0을 수입 및 수출 형식으로 지원합니다. Scene 개체는 OBJ, FBX, STL 또는 다른 출처 파일에서 인구를 얻을 수 있으며 다음에 작성할 수 있습니다. .gltf (JSON + 외부 바이너리) 또는 .glb (단일 바이너리 컨테이니어) 하나의 깃발을 설정하여 GltfSaveOptions.
단계별 가이드
단계 1 : 설치 @aspose/3d
asposefoss/3d is not yet published — build from source until it ships. See the project README for build instructions.
Node.js 18 또는 이후의 활성화 확인:
node --version # must be >= 16.0.0단계 2: 수입 장면, GltfSaveOptions 및 GlTfFormat
import { Scene } from '@aspose/3d';
import { GltfSaveOptions, GltfFormat } from '@aspose/3d/formats/gltf';GltfFormat 묘사기 형식이 전달된 경우 scene.save(). GltfSaveOptions 모든 수출 구성이 적용됩니다.
또한 원본 파일 (예 : OBJ)을 업로드하는 경우 해당 로드 옵션을 가져오십시오.:
import { ObjLoadOptions } from '@aspose/3d/formats/obj';단계 3: 장면을 만들거나 충전하십시오.
옵션 A: 기존 파일에서 다운로드 (OBJ → GLB 변환):
import { Scene } from '@aspose/3d';
import { ObjLoadOptions } from '@aspose/3d/formats/obj';
import { GltfSaveOptions, GltfFormat } from '@aspose/3d/formats/gltf';
const scene = new Scene();
scene.open('model.obj', new ObjLoadOptions());옵션 B : 최소한의 장면을 프로그래밍으로 만드십시오.:
import { Scene, Node, Mesh } from '@aspose/3d';
import { GltfSaveOptions, GltfFormat } from '@aspose/3d/formats/gltf';
const scene = new Scene();
const childNode = new Node('cube');
scene.rootNode.addChildNode(childNode);
// Attach geometry to childNode as needed
단계 4: GltfSaveOptions 설정
GltfSaveOptions 출력 형식과 암호화 세부 사항을 제어합니다.
const saveOpts = new GltfSaveOptions();
// Set to true for a single binary .glb file
// Set to false (default) for JSON .gltf + separate .bin
saveOpts.binaryMode = true;추가 옵션을 설정할 수 있습니다 :
| 부동산 | 유형 | 가상화 | 효과가 |
|---|---|---|---|
binaryMode | boolean | false | true → GLB, false 스 JSON |
flipTexCoordV | boolean | true | Flip UV 수직 좌석 엔진 호환성 |
단계 5 : 스케치.save()를 사용하여 저장합니다.
출구 경로를 통과하고, 그 GltfFormat 설명기, 그리고 구성된 옵션 :
import { Scene } from '@aspose/3d';
import { ObjLoadOptions } from '@aspose/3d/formats/obj';
import { GltfSaveOptions, GltfFormat } from '@aspose/3d/formats/gltf';
const scene = new Scene();
scene.open('model.obj', new ObjLoadOptions());
const saveOpts = new GltfSaveOptions();
saveOpts.binaryMode = true; // produce .glb
scene.save('output.glb', GltfFormat.getInstance(), saveOpts);
console.log('Converted to GLB successfully');JSON을 만드는 방법 .gltf 파일 대신 :
saveOpts.binaryMode = false;
scene.save('output.gltf', GltfFormat.getInstance(), saveOpts);
console.log('Exported to glTF JSON successfully');단계 6 : 출력 파일을 확인합니다.
출력 파일이 존재하고 0 크기가 아닌지 확인하십시오.:
import * as fs from 'fs';
const outputPath = 'output.glb';
const stats = fs.statSync(outputPath);
console.log(`Output file size: ${stats.size} bytes`);
if (stats.size === 0) {
throw new Error('Export produced an empty file: check scene content');
}라운드 트리프 확인을 위해 GLB를 다시 업로드하고 노드 계산을 검사하십시오.:
import { Scene } from '@aspose/3d';
import { GltfLoadOptions } from '@aspose/3d/formats/gltf';
const verify = new Scene();
verify.open('output.glb', new GltfLoadOptions());
let nodeCount = 0;
function countNodes(node: any): void {
nodeCount++;
for (const child of node.childNodes) countNodes(child);
}
countNodes(verify.rootNode);
console.log(`Round-trip verification: ${nodeCount} node(s) in output`);일반적인 문제와 해결책
OBJ 자료 파일은 수출 후 발견되지 않았습니다. OBJ를 통해 저축할 때 scene.save('output.obj'),그리고, The .mtl 파일은 옆에 기록되어 있습니다. .obj 파일이 자동으로 작성됩니다.출력 디렉토리가 글쓰기 가능하고 두 파일 모두 함께 보관되어 있는지 확인합니다.
출력 .glb 예상보다 작습니다 / 메시지가 없어집니다. 충전된 장면에는 개체가 없는 노드가 있다면 (예를 들어 OBJ에서 빈 그룹), GLB는 그 노드를 지질로 포함하지 않습니다. mesh.controlPoints.length > 0 저축하기 전에.
모듈을 찾을 수 없습니다 ‘@aspose/3d/formats/gltf’ Node.js 18+에 있는지 확인하고, 그 @aspose/3d 동일한 곳에 설치되어 있습니다. node_modules 당신의 입장점으로서. Run npm ls @aspose/3d 버전을 확인하려면 24.12.0 또는 그 이후입니다.
GltfFormat.getInstance()는 정해지지 않은 상태로 돌아갑니다. 이것은 주요 버전 사이의 오류를 나타냅니다. @aspose/3d 패키지 및 캐시된 오래된 버전. 삭제 node_modules 그리고 package-lock.json,그리고 그 다음에 달리기 npm install 다시 한 번.
텍스트가 GLB 생산에서 부족합니다. 보안 binaryMode = true GLB 자체를 생산하기 위해 설정되어 있습니다. glTF JSON 출력의 경우, 텍스트 이미지 파일은 출력을 통해 참조되기 때문에 출력이 있는 파일과 함께 있어야 합니다.
유형 오류: ‘GltfSaveOptions’의 주장은 부여되지 않습니다. 둘 다 보장하라. Scene 그리고 GltfSaveOptions 혼합 설치 (글로벌 + 로컬)는 인터페이스 오류를 일으킬 수 있습니다.
자주 묻는 질문 (FAQ)
GLTF와 GLB의 차이점은 무엇입니까? 스코트 2.0 JSON (.gltf) 스케치 그래픽을 인간 읽을 수있는 JSON 파일로 별도로 저장합니다. .bin 과 사진 파일. GLB (.glb모든 것을 하나의 바이너리 컨테이니어로 포장합니다. binaryMode = true GLB에 대한 정보, false JSON GLTF에 대한 정보.
코드에 완전히 구축 된 장면을 수출 할 수 있습니까 (원본 파일이 없음)? 창조 A Scene,추가하기 Node 개체, 접착제 Mesh 다른 사람들, 그리고 전화 scene.save().장면은 충전된 파일에서 출처할 필요가 없습니다.
GST는 무제한으로 납부되었습니까? 지질학 및 변환, 예. 재료는 가능한 경우 glTF PBR 재질 속성에 맵을 삽입합니다. FBX 재물 확장품은 완벽하게 회전하지 않을 수 있습니다.
대신 STL 또는 3MF로 수출 할 수 있습니까? 예. 패턴은 동일합니다; 해당 형식의 가져오기 *SaveOptions 그리고 *Format.getInstance():
import { StlSaveOptions, StlFormat } from '@aspose/3d/formats/stl';
const opts = new StlSaveOptions();
scene.save('output.stl', StlFormat.getInstance(), opts);scene.save()는 비동기적으로 실행되나요? 아니오 니. scene.save() 일동으로 삽입하십시오.당신이 큰 수출 동안 이벤트 루프를 차단하는 것을 피해야한다면 노동자 스트립에 그것을 넣어.
어떤 Node.js 버전이 지원되는가? Node.js 18, 20, 및 22+는 지원되지 않습니다.Node .js 16 및 이전은 지원됩니다.