UNPKG

@babylonjs/loaders

Version:

The Babylon.js file loaders library is an extension you can use to load different 3D file types into a Babylon scene.

1,074 lines (1,073 loc) 95.8 kB
import { Deferred } from "@babylonjs/core/Misc/deferred"; import { Quaternion, Color3, Vector3, Matrix } from "@babylonjs/core/Maths/math"; import { LoadFileError, Tools } from "@babylonjs/core/Misc/tools"; import { Camera } from "@babylonjs/core/Cameras/camera"; import { FreeCamera } from "@babylonjs/core/Cameras/freeCamera"; import { AnimationGroup } from "@babylonjs/core/Animations/animationGroup"; import { Animation } from "@babylonjs/core/Animations/animation"; import { Bone } from "@babylonjs/core/Bones/bone"; import { Skeleton } from "@babylonjs/core/Bones/skeleton"; import { Material } from "@babylonjs/core/Materials/material"; import { PBRMaterial } from "@babylonjs/core/Materials/PBR/pbrMaterial"; import { Texture } from "@babylonjs/core/Materials/Textures/texture"; import { TransformNode } from "@babylonjs/core/Meshes/transformNode"; import { Buffer, VertexBuffer } from "@babylonjs/core/Meshes/buffer"; import { Geometry } from "@babylonjs/core/Meshes/geometry"; import { Mesh } from "@babylonjs/core/Meshes/mesh"; import { MorphTarget } from "@babylonjs/core/Morph/morphTarget"; import { MorphTargetManager } from "@babylonjs/core/Morph/morphTargetManager"; import { SceneLoaderProgressEvent } from "@babylonjs/core/Loading/sceneLoader"; import { GLTFFileLoader, GLTFLoaderState, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode } from "../glTFFileLoader"; import { AnimationKeyInterpolation } from '@babylonjs/core/Animations/animationKey'; /** * Helper class for working with arrays when loading the glTF asset */ var ArrayItem = /** @class */ (function () { function ArrayItem() { } /** * Gets an item from the given array. * @param context The context when loading the asset * @param array The array to get the item from * @param index The index to the array * @returns The array item */ ArrayItem.Get = function (context, array, index) { if (!array || index == undefined || !array[index]) { throw new Error(context + ": Failed to find index (" + index + ")"); } return array[index]; }; /** * Assign an `index` field to each item of the given array. * @param array The array of items */ ArrayItem.Assign = function (array) { if (array) { for (var index = 0; index < array.length; index++) { array[index].index = index; } } }; return ArrayItem; }()); export { ArrayItem }; /** * The glTF 2.0 loader */ var GLTFLoader = /** @class */ (function () { /** @hidden */ function GLTFLoader(parent) { /** @hidden */ this._completePromises = new Array(); this._disposed = false; this._state = null; this._extensions = {}; this._defaultBabylonMaterialData = {}; this._requests = new Array(); this._parent = parent; } /** * Registers a loader extension. * @param name The name of the loader extension. * @param factory The factory function that creates the loader extension. */ GLTFLoader.RegisterExtension = function (name, factory) { if (GLTFLoader.UnregisterExtension(name)) { Tools.Warn("Extension with the name '" + name + "' already exists"); } GLTFLoader._ExtensionFactories[name] = factory; // Keep the order of registration so that extensions registered first are called first. GLTFLoader._ExtensionNames.push(name); }; /** * Unregisters a loader extension. * @param name The name of the loader extenion. * @returns A boolean indicating whether the extension has been unregistered */ GLTFLoader.UnregisterExtension = function (name) { if (!GLTFLoader._ExtensionFactories[name]) { return false; } delete GLTFLoader._ExtensionFactories[name]; var index = GLTFLoader._ExtensionNames.indexOf(name); if (index !== -1) { GLTFLoader._ExtensionNames.splice(index, 1); } return true; }; Object.defineProperty(GLTFLoader.prototype, "state", { /** * Gets the loader state. */ get: function () { return this._state; }, enumerable: true, configurable: true }); Object.defineProperty(GLTFLoader.prototype, "gltf", { /** * The glTF object parsed from the JSON. */ get: function () { return this._gltf; }, enumerable: true, configurable: true }); Object.defineProperty(GLTFLoader.prototype, "babylonScene", { /** * The Babylon scene when loading the asset. */ get: function () { return this._babylonScene; }, enumerable: true, configurable: true }); Object.defineProperty(GLTFLoader.prototype, "rootBabylonMesh", { /** * The root Babylon mesh when loading the asset. */ get: function () { return this._rootBabylonMesh; }, enumerable: true, configurable: true }); /** @hidden */ GLTFLoader.prototype.dispose = function () { if (this._disposed) { return; } this._disposed = true; for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { var request = _a[_i]; request.abort(); } this._requests.length = 0; this._completePromises.length = 0; for (var name_1 in this._extensions) { var extension = this._extensions[name_1]; if (extension.dispose) { this._extensions[name_1].dispose(); } } this._extensions = {}; delete this._gltf; delete this._babylonScene; delete this._rootBabylonMesh; delete this._progressCallback; this._parent._clear(); }; /** @hidden */ GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) { var _this = this; return Promise.resolve().then(function () { _this._babylonScene = scene; _this._rootUrl = rootUrl; _this._fileName = fileName || "scene"; _this._progressCallback = onProgress; _this._loadData(data); var nodes = null; if (meshesNames) { var nodeMap_1 = {}; if (_this._gltf.nodes) { for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) { var node = _a[_i]; if (node.name) { nodeMap_1[node.name] = node.index; } } } var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames]; nodes = names.map(function (name) { var node = nodeMap_1[name]; if (node === undefined) { throw new Error("Failed to find node '" + name + "'"); } return node; }); } return _this._loadAsync(nodes, function () { return { meshes: _this._getMeshes(), particleSystems: [], skeletons: _this._getSkeletons(), animationGroups: _this._getAnimationGroups() }; }); }); }; /** @hidden */ GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) { var _this = this; return Promise.resolve().then(function () { _this._babylonScene = scene; _this._rootUrl = rootUrl; _this._fileName = fileName || "scene"; _this._progressCallback = onProgress; _this._loadData(data); return _this._loadAsync(null, function () { return undefined; }); }); }; GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) { var _this = this; return Promise.resolve().then(function () { _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/"; _this._loadExtensions(); _this._checkExtensions(); var loadingToReadyCounterName = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.READY]; var loadingToCompleteCounterName = GLTFLoaderState[GLTFLoaderState.LOADING] + " => " + GLTFLoaderState[GLTFLoaderState.COMPLETE]; _this._parent._startPerformanceCounter(loadingToReadyCounterName); _this._parent._startPerformanceCounter(loadingToCompleteCounterName); _this._setState(GLTFLoaderState.LOADING); _this._extensionsOnLoading(); var promises = new Array(); if (nodes) { promises.push(_this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 })); } else if (_this._gltf.scene != undefined || (_this._gltf.scenes && _this._gltf.scenes[0])) { var scene = ArrayItem.Get("/scene", _this._gltf.scenes, _this._gltf.scene || 0); promises.push(_this.loadSceneAsync("/scenes/" + scene.index, scene)); } if (_this._parent.compileMaterials) { promises.push(_this._compileMaterialsAsync()); } if (_this._parent.compileShadowGenerators) { promises.push(_this._compileShadowGeneratorsAsync()); } var resultPromise = Promise.all(promises).then(function () { if (_this._rootBabylonMesh) { _this._rootBabylonMesh.setEnabled(true); } _this._setState(GLTFLoaderState.READY); _this._extensionsOnReady(); _this._startAnimations(); return resultFunc(); }); resultPromise.then(function () { _this._parent._endPerformanceCounter(loadingToReadyCounterName); Tools.SetImmediate(function () { if (!_this._disposed) { Promise.all(_this._completePromises).then(function () { _this._parent._endPerformanceCounter(loadingToCompleteCounterName); _this._setState(GLTFLoaderState.COMPLETE); _this._parent.onCompleteObservable.notifyObservers(undefined); _this._parent.onCompleteObservable.clear(); _this.dispose(); }, function (error) { _this._parent.onErrorObservable.notifyObservers(error); _this._parent.onErrorObservable.clear(); _this.dispose(); }); } }); }); return resultPromise; }, function (error) { if (!_this._disposed) { _this._parent.onErrorObservable.notifyObservers(error); _this._parent.onErrorObservable.clear(); _this.dispose(); } throw error; }); }; GLTFLoader.prototype._loadData = function (data) { this._gltf = data.json; this._setupData(); if (data.bin) { var buffers = this._gltf.buffers; if (buffers && buffers[0] && !buffers[0].uri) { var binaryBuffer = buffers[0]; if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) { Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")"); } binaryBuffer._data = Promise.resolve(data.bin); } else { Tools.Warn("Unexpected BIN chunk"); } } }; GLTFLoader.prototype._setupData = function () { ArrayItem.Assign(this._gltf.accessors); ArrayItem.Assign(this._gltf.animations); ArrayItem.Assign(this._gltf.buffers); ArrayItem.Assign(this._gltf.bufferViews); ArrayItem.Assign(this._gltf.cameras); ArrayItem.Assign(this._gltf.images); ArrayItem.Assign(this._gltf.materials); ArrayItem.Assign(this._gltf.meshes); ArrayItem.Assign(this._gltf.nodes); ArrayItem.Assign(this._gltf.samplers); ArrayItem.Assign(this._gltf.scenes); ArrayItem.Assign(this._gltf.skins); ArrayItem.Assign(this._gltf.textures); if (this._gltf.nodes) { var nodeParents = {}; for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) { var node = _a[_i]; if (node.children) { for (var _b = 0, _c = node.children; _b < _c.length; _b++) { var index = _c[_b]; nodeParents[index] = node.index; } } } var rootNode = this._createRootNode(); for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) { var node = _e[_d]; var parentIndex = nodeParents[node.index]; node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex]; } } }; GLTFLoader.prototype._loadExtensions = function () { for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { var name_2 = _a[_i]; var extension = GLTFLoader._ExtensionFactories[name_2](this); this._extensions[name_2] = extension; this._parent.onExtensionLoadedObservable.notifyObservers(extension); } this._parent.onExtensionLoadedObservable.clear(); }; GLTFLoader.prototype._checkExtensions = function () { if (this._gltf.extensionsRequired) { for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) { var name_3 = _a[_i]; var extension = this._extensions[name_3]; if (!extension || !extension.enabled) { throw new Error("Require extension " + name_3 + " is not available"); } } } }; GLTFLoader.prototype._setState = function (state) { this._state = state; this.log(GLTFLoaderState[this._state]); }; GLTFLoader.prototype._createRootNode = function () { this._rootBabylonMesh = new Mesh("__root__", this._babylonScene); this._rootBabylonMesh.setEnabled(false); var rootNode = { _babylonTransformNode: this._rootBabylonMesh, index: -1 }; switch (this._parent.coordinateSystemMode) { case GLTFLoaderCoordinateSystemMode.AUTO: { if (!this._babylonScene.useRightHandedSystem) { rootNode.rotation = [0, 1, 0, 0]; rootNode.scale = [1, 1, -1]; GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh); } break; } case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: { this._babylonScene.useRightHandedSystem = true; break; } default: { throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")"); } } this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh); return rootNode; }; /** * Loads a glTF scene. * @param context The context when loading the asset * @param scene The glTF scene property * @returns A promise that resolves when the load is complete */ GLTFLoader.prototype.loadSceneAsync = function (context, scene) { var _this = this; var extensionPromise = this._extensionsLoadSceneAsync(context, scene); if (extensionPromise) { return extensionPromise; } var promises = new Array(); this.logOpen(context + " " + (scene.name || "")); if (scene.nodes) { for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) { var index = _a[_i]; var node = ArrayItem.Get(context + "/nodes/" + index, this._gltf.nodes, index); promises.push(this.loadNodeAsync("/nodes/" + node.index, node, function (babylonMesh) { babylonMesh.parent = _this._rootBabylonMesh; })); } } // Link all Babylon bones for each glTF node with the corresponding Babylon transform node. // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D. if (this._gltf.nodes) { for (var _b = 0, _c = this._gltf.nodes; _b < _c.length; _b++) { var node = _c[_b]; if (node._babylonTransformNode && node._babylonBones) { for (var _d = 0, _e = node._babylonBones; _d < _e.length; _d++) { var babylonBone = _e[_d]; babylonBone.linkTransformNode(node._babylonTransformNode); } } } } promises.push(this._loadAnimationsAsync()); this.logClose(); return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._forEachPrimitive = function (node, callback) { if (node._primitiveBabylonMeshes) { for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) { var babylonMesh = _a[_i]; callback(babylonMesh); } } }; GLTFLoader.prototype._getMeshes = function () { var meshes = new Array(); // Root mesh is always first. meshes.push(this._rootBabylonMesh); var nodes = this._gltf.nodes; if (nodes) { for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node = nodes_1[_i]; this._forEachPrimitive(node, function (babylonMesh) { meshes.push(babylonMesh); }); } } return meshes; }; GLTFLoader.prototype._getSkeletons = function () { var skeletons = new Array(); var skins = this._gltf.skins; if (skins) { for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) { var skin = skins_1[_i]; if (skin._data) { skeletons.push(skin._data.babylonSkeleton); } } } return skeletons; }; GLTFLoader.prototype._getAnimationGroups = function () { var animationGroups = new Array(); var animations = this._gltf.animations; if (animations) { for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) { var animation = animations_1[_i]; if (animation._babylonAnimationGroup) { animationGroups.push(animation._babylonAnimationGroup); } } } return animationGroups; }; GLTFLoader.prototype._startAnimations = function () { switch (this._parent.animationStartMode) { case GLTFLoaderAnimationStartMode.NONE: { // do nothing break; } case GLTFLoaderAnimationStartMode.FIRST: { var babylonAnimationGroups = this._getAnimationGroups(); if (babylonAnimationGroups.length !== 0) { babylonAnimationGroups[0].start(true); } break; } case GLTFLoaderAnimationStartMode.ALL: { var babylonAnimationGroups = this._getAnimationGroups(); for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) { var babylonAnimationGroup = babylonAnimationGroups_1[_i]; babylonAnimationGroup.start(true); } break; } default: { Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")"); return; } } }; /** * Loads a glTF node. * @param context The context when loading the asset * @param node The glTF node property * @param assign A function called synchronously after parsing the glTF properties * @returns A promise that resolves with the loaded Babylon mesh when the load is complete */ GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) { var _this = this; if (assign === void 0) { assign = function () { }; } var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign); if (extensionPromise) { return extensionPromise; } if (node._babylonTransformNode) { throw new Error(context + ": Invalid recursive node hierarchy"); } var promises = new Array(); this.logOpen(context + " " + (node.name || "")); var loadNode = function (babylonTransformNode) { GLTFLoader.AddPointerMetadata(babylonTransformNode, context); GLTFLoader._LoadTransform(node, babylonTransformNode); if (node.camera != undefined) { var camera = ArrayItem.Get(context + "/camera", _this._gltf.cameras, node.camera); promises.push(_this.loadCameraAsync("/cameras/" + camera.index, camera, function (babylonCamera) { babylonCamera.parent = babylonTransformNode; })); } if (node.children) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var index = _a[_i]; var childNode = ArrayItem.Get(context + "/children/" + index, _this._gltf.nodes, index); promises.push(_this.loadNodeAsync("/nodes/" + childNode.index, childNode, function (childBabylonMesh) { childBabylonMesh.parent = babylonTransformNode; })); } } assign(babylonTransformNode); }; if (node.mesh == undefined) { var nodeName = node.name || "node" + node.index; node._babylonTransformNode = new TransformNode(nodeName, this._babylonScene); loadNode(node._babylonTransformNode); } else { var mesh = ArrayItem.Get(context + "/mesh", this._gltf.meshes, node.mesh); promises.push(this._loadMeshAsync("/meshes/" + mesh.index, node, mesh, loadNode)); } this.logClose(); return Promise.all(promises).then(function () { _this._forEachPrimitive(node, function (babylonMesh) { babylonMesh.refreshBoundingInfo(true); }); return node._babylonTransformNode; }); }; GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, assign) { var primitives = mesh.primitives; if (!primitives || !primitives.length) { throw new Error(context + ": Primitives are missing"); } if (primitives[0].index == undefined) { ArrayItem.Assign(primitives); } var promises = new Array(); this.logOpen(context + " " + (mesh.name || "")); var name = node.name || "node" + node.index; if (primitives.length === 1) { var primitive = mesh.primitives[0]; promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name, node, mesh, primitive, function (babylonMesh) { node._babylonTransformNode = babylonMesh; node._primitiveBabylonMeshes = [babylonMesh]; })); } else { node._babylonTransformNode = new TransformNode(name, this._babylonScene); node._primitiveBabylonMeshes = []; for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) { var primitive = primitives_1[_i]; promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name + "_primitive" + primitive.index, node, mesh, primitive, function (babylonMesh) { babylonMesh.parent = node._babylonTransformNode; node._primitiveBabylonMeshes.push(babylonMesh); })); } } if (node.skin != undefined) { var skin = ArrayItem.Get(context + "/skin", this._gltf.skins, node.skin); promises.push(this._loadSkinAsync("/skins/" + skin.index, node, skin)); } assign(node._babylonTransformNode); this.logClose(); return Promise.all(promises).then(function () { return node._babylonTransformNode; }); }; GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) { var _this = this; this.logOpen("" + context); var canInstance = (node.skin == undefined && !mesh.primitives[0].targets); var babylonAbstractMesh; var promise; var instanceData = primitive._instanceData; if (canInstance && instanceData) { babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name); promise = instanceData.promise; } else { var promises = new Array(); var babylonMesh_1 = new Mesh(name, this._babylonScene); this._createMorphTargets(context, node, mesh, primitive, babylonMesh_1); promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh_1).then(function (babylonGeometry) { return _this._loadMorphTargetsAsync(context, primitive, babylonMesh_1, babylonGeometry).then(function () { babylonGeometry.applyToMesh(babylonMesh_1); }); })); var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode); if (primitive.material == undefined) { var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode]; if (!babylonMaterial) { babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode); this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial); this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial; } babylonMesh_1.material = babylonMaterial; } else { var material = ArrayItem.Get(context + "/material", this._gltf.materials, primitive.material); promises.push(this._loadMaterialAsync("/materials/" + material.index, material, babylonMesh_1, babylonDrawMode, function (babylonMaterial) { babylonMesh_1.material = babylonMaterial; })); } promise = Promise.all(promises); if (canInstance) { primitive._instanceData = { babylonSourceMesh: babylonMesh_1, promise: promise }; } babylonAbstractMesh = babylonMesh_1; } GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context); this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh); assign(babylonAbstractMesh); this.logClose(); return promise.then(function () { return babylonAbstractMesh; }); }; GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { var _this = this; var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh); if (extensionPromise) { return extensionPromise; } var attributes = primitive.attributes; if (!attributes) { throw new Error(context + ": Attributes are missing"); } var promises = new Array(); var babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene); if (primitive.indices == undefined) { babylonMesh.isUnIndexed = true; } else { var accessor = ArrayItem.Get(context + "/indices", this._gltf.accessors, primitive.indices); promises.push(this._loadIndicesAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { babylonGeometry.setIndices(data); })); } var loadAttribute = function (attribute, kind, callback) { if (attributes[attribute] == undefined) { return; } babylonMesh._delayInfo = babylonMesh._delayInfo || []; if (babylonMesh._delayInfo.indexOf(kind) === -1) { babylonMesh._delayInfo.push(kind); } var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]); promises.push(_this._loadVertexAccessorAsync("/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) { babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count); })); if (callback) { callback(accessor); } }; loadAttribute("POSITION", VertexBuffer.PositionKind); loadAttribute("NORMAL", VertexBuffer.NormalKind); loadAttribute("TANGENT", VertexBuffer.TangentKind); loadAttribute("TEXCOORD_0", VertexBuffer.UVKind); loadAttribute("TEXCOORD_1", VertexBuffer.UV2Kind); loadAttribute("JOINTS_0", VertexBuffer.MatricesIndicesKind); loadAttribute("WEIGHTS_0", VertexBuffer.MatricesWeightsKind); loadAttribute("COLOR_0", VertexBuffer.ColorKind, function (accessor) { if (accessor.type === "VEC4" /* VEC4 */) { babylonMesh.hasVertexAlpha = true; } }); return Promise.all(promises).then(function () { return babylonGeometry; }); }; GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) { if (!primitive.targets) { return; } if (node._numMorphTargets == undefined) { node._numMorphTargets = primitive.targets.length; } else if (primitive.targets.length !== node._numMorphTargets) { throw new Error(context + ": Primitives do not have the same number of targets"); } babylonMesh.morphTargetManager = new MorphTargetManager(); for (var index = 0; index < primitive.targets.length; index++) { var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0; babylonMesh.morphTargetManager.addTarget(new MorphTarget("morphTarget" + index, weight)); // TODO: tell the target whether it has positions, normals, tangents } }; GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) { if (!primitive.targets) { return Promise.resolve(); } var promises = new Array(); var morphTargetManager = babylonMesh.morphTargetManager; for (var index = 0; index < morphTargetManager.numTargets; index++) { var babylonMorphTarget = morphTargetManager.getTarget(index); promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget)); } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) { var _this = this; var promises = new Array(); var loadAttribute = function (attribute, kind, setData) { if (attributes[attribute] == undefined) { return; } var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind); if (!babylonVertexBuffer) { return; } var accessor = ArrayItem.Get(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]); promises.push(_this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { setData(babylonVertexBuffer, data); })); }; loadAttribute("POSITION", VertexBuffer.PositionKind, function (babylonVertexBuffer, data) { babylonVertexBuffer.forEach(data.length, function (value, index) { data[index] += value; }); babylonMorphTarget.setPositions(data); }); loadAttribute("NORMAL", VertexBuffer.NormalKind, function (babylonVertexBuffer, data) { babylonVertexBuffer.forEach(data.length, function (value, index) { data[index] += value; }); babylonMorphTarget.setNormals(data); }); loadAttribute("TANGENT", VertexBuffer.TangentKind, function (babylonVertexBuffer, data) { var dataIndex = 0; babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) { // Tangent data for morph targets is stored as xyz delta. // The vertexData.tangent is stored as xyzw. // So we need to skip every fourth vertexData.tangent. if (((index + 1) % 4) !== 0) { data[dataIndex++] += value; } }); babylonMorphTarget.setTangents(data); }); return Promise.all(promises).then(function () { }); }; GLTFLoader._LoadTransform = function (node, babylonNode) { // Ignore the TRS of skinned nodes. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) if (node.skin != undefined) { return; } var position = Vector3.Zero(); var rotation = Quaternion.Identity(); var scaling = Vector3.One(); if (node.matrix) { var matrix = Matrix.FromArray(node.matrix); matrix.decompose(scaling, rotation, position); } else { if (node.translation) { position = Vector3.FromArray(node.translation); } if (node.rotation) { rotation = Quaternion.FromArray(node.rotation); } if (node.scale) { scaling = Vector3.FromArray(node.scale); } } babylonNode.position = position; babylonNode.rotationQuaternion = rotation; babylonNode.scaling = scaling; }; GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) { var _this = this; var assignSkeleton = function (skeleton) { _this._forEachPrimitive(node, function (babylonMesh) { babylonMesh.skeleton = skeleton; }); }; if (skin._data) { assignSkeleton(skin._data.babylonSkeleton); return skin._data.promise; } var skeletonId = "skeleton" + skin.index; var babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene); // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) babylonSkeleton.overrideMesh = this._rootBabylonMesh; this._loadBones(context, skin, babylonSkeleton); assignSkeleton(babylonSkeleton); var promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) { _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData); }); skin._data = { babylonSkeleton: babylonSkeleton, promise: promise }; return promise; }; GLTFLoader.prototype._loadBones = function (context, skin, babylonSkeleton) { var babylonBones = {}; for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) { var index = _a[_i]; var node = ArrayItem.Get(context + "/joints/" + index, this._gltf.nodes, index); this._loadBone(node, skin, babylonSkeleton, babylonBones); } }; GLTFLoader.prototype._loadBone = function (node, skin, babylonSkeleton, babylonBones) { var babylonBone = babylonBones[node.index]; if (babylonBone) { return babylonBone; } var babylonParentBone = null; if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) { babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones); } var boneIndex = skin.joints.indexOf(node.index); babylonBone = new Bone(node.name || "joint" + node.index, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex); babylonBones[node.index] = babylonBone; node._babylonBones = node._babylonBones || []; node._babylonBones.push(babylonBone); return babylonBone; }; GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) { if (skin.inverseBindMatrices == undefined) { return Promise.resolve(null); } var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices); return this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor); }; GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) { for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) { var babylonBone = _a[_i]; var baseMatrix = Matrix.Identity(); var boneIndex = babylonBone._index; if (inverseBindMatricesData && boneIndex !== -1) { Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix); baseMatrix.invertToRef(baseMatrix); } var babylonParentBone = babylonBone.getParent(); if (babylonParentBone) { baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix); } babylonBone.updateMatrix(baseMatrix, false, false); babylonBone._updateDifferenceMatrix(undefined, false); } }; GLTFLoader.prototype._getNodeMatrix = function (node) { return node.matrix ? Matrix.FromArray(node.matrix) : Matrix.Compose(node.scale ? Vector3.FromArray(node.scale) : Vector3.One(), node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(), node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero()); }; /** * Loads a glTF camera. * @param context The context when loading the asset * @param camera The glTF camera property * @param assign A function called synchronously after parsing the glTF properties * @returns A promise that resolves with the loaded Babylon camera when the load is complete */ GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) { if (assign === void 0) { assign = function () { }; } var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign); if (extensionPromise) { return extensionPromise; } var promises = new Array(); this.logOpen(context + " " + (camera.name || "")); var babylonCamera = new FreeCamera(camera.name || "camera" + camera.index, Vector3.Zero(), this._babylonScene, false); babylonCamera.rotation = new Vector3(0, Math.PI, 0); switch (camera.type) { case "perspective" /* PERSPECTIVE */: { var perspective = camera.perspective; if (!perspective) { throw new Error(context + ": Camera perspective properties are missing"); } babylonCamera.fov = perspective.yfov; babylonCamera.minZ = perspective.znear; babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE; break; } case "orthographic" /* ORTHOGRAPHIC */: { if (!camera.orthographic) { throw new Error(context + ": Camera orthographic properties are missing"); } babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA; babylonCamera.orthoLeft = -camera.orthographic.xmag; babylonCamera.orthoRight = camera.orthographic.xmag; babylonCamera.orthoBottom = -camera.orthographic.ymag; babylonCamera.orthoTop = camera.orthographic.ymag; babylonCamera.minZ = camera.orthographic.znear; babylonCamera.maxZ = camera.orthographic.zfar; break; } default: { throw new Error(context + ": Invalid camera type (" + camera.type + ")"); } } GLTFLoader.AddPointerMetadata(babylonCamera, context); this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera); assign(babylonCamera); return Promise.all(promises).then(function () { return babylonCamera; }); }; GLTFLoader.prototype._loadAnimationsAsync = function () { var animations = this._gltf.animations; if (!animations) { return Promise.resolve(); } var promises = new Array(); for (var index = 0; index < animations.length; index++) { var animation = animations[index]; promises.push(this.loadAnimationAsync("/animations/" + animation.index, animation)); } return Promise.all(promises).then(function () { }); }; /** * Loads a glTF animation. * @param context The context when loading the asset * @param animation The glTF animation property * @returns A promise that resolves with the loaded Babylon animation group when the load is complete */ GLTFLoader.prototype.loadAnimationAsync = function (context, animation) { var promise = this._extensionsLoadAnimationAsync(context, animation); if (promise) { return promise; } var babylonAnimationGroup = new AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene); animation._babylonAnimationGroup = babylonAnimationGroup; var promises = new Array(); ArrayItem.Assign(animation.channels); ArrayItem.Assign(animation.samplers); for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) { var channel = _a[_i]; promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup)); } return Promise.all(promises).then(function () { babylonAnimationGroup.normalize(0); return babylonAnimationGroup; }); }; GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) { var _this = this; if (channel.target.node == undefined) { return Promise.resolve(); } var targetNode = ArrayItem.Get(context + "/target/node", this._gltf.nodes, channel.target.node); // Ignore animations that have no animation targets. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) || (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonTransformNode)) { return Promise.resolve(); } var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler); return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) { var targetPath; var animationType; switch (channel.target.path) { case "translation" /* TRANSLATION */: { targetPath = "position"; animationType = Animation.ANIMATIONTYPE_VECTOR3; break; } case "rotation" /* ROTATION */: { targetPath = "rotationQuaternion"; animationType = Animation.ANIMATIONTYPE_QUATERNION; break; } case "scale" /* SCALE */: { targetPath = "scaling"; animationType = Animation.ANIMATIONTYPE_VECTOR3; break; } case "weights" /* WEIGHTS */: { targetPath = "influence"; animationType = Animation.ANIMATIONTYPE_FLOAT; break; } default: { throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")"); } } var outputBufferOffset = 0; var getNextOutputValue; switch (targetPath) { case "position": { getNextOutputValue = function () { var value = Vector3.FromArray(data.output, outputBufferOffset); outputBufferOffset += 3; return value; }; break; } case "rotationQuaternion": { getNextOutputValue = function () { var value = Quaternion.FromArray(data.output, outputBufferOffset); outputBufferOffset += 4; return value; }; break; } case "scaling": { getNextOutputValue = function () { var value = Vector3.FromArray(data.output, outputBufferOffset); outputBufferOffset += 3; return value; }; break; } case "influence": { getNextOutputValue = function () { var value = new Array(targetNode._numMorphTargets); for (var i = 0; i < targetNode._numMorphTargets; i++) { value[i] = data.output[outputBufferOffset++]; } return value; }; break; } } var getNextKey; switch (data.interpolation) { case "STEP" /* STEP */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], value: getNextOutputValue(), interpolation: AnimationKeyInterpolation.STEP }); }; break; } case "LINEAR" /* LINEAR */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], value: getNextOutputValue() }); }; break; } case "CUBICSPLINE" /* CUBICSPLINE */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], inTangent: getNextOutputValue(), value: getNextOutputValue(), outTangent: getNextOutputValue() }); }; break; } } var keys = new Array(data.input.length); for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) { keys[frameIndex] = getNextKey(frameIndex); } if (targetPath === "influence") { var _loop_1 = function (targetIndex) {