2017-07-19 17:56:24 -04:00
|
|
|
'use strict';
|
|
|
|
var Cesium = require('cesium');
|
|
|
|
var getJsonBufferPadded = require('./getJsonBufferPadded');
|
|
|
|
|
2017-07-29 13:23:33 -04:00
|
|
|
var defined = Cesium.defined;
|
2017-07-19 17:56:24 -04:00
|
|
|
|
|
|
|
module.exports = gltfToGlb;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert a glTF to binary glTF.
|
|
|
|
*
|
2017-07-29 13:23:33 -04:00
|
|
|
* The glTF is expected to have a single buffer and all embedded resources stored in bufferViews.
|
2017-07-27 11:23:12 -04:00
|
|
|
*
|
2017-07-29 13:23:33 -04:00
|
|
|
* @param {Object} gltf The glTF asset.
|
|
|
|
* @param {Buffer} binaryBuffer The binary buffer.
|
|
|
|
* @returns {Buffer} The glb buffer.
|
2017-07-19 17:56:24 -04:00
|
|
|
*
|
|
|
|
* @private
|
|
|
|
*/
|
2017-07-29 13:23:33 -04:00
|
|
|
function gltfToGlb(gltf, binaryBuffer) {
|
2017-07-19 17:56:24 -04:00
|
|
|
var buffer = gltf.buffers[0];
|
2017-07-29 13:23:33 -04:00
|
|
|
if (defined(buffer.uri)) {
|
2017-07-19 17:56:24 -04:00
|
|
|
binaryBuffer = Buffer.alloc(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create padded binary scene string
|
|
|
|
var jsonBuffer = getJsonBufferPadded(gltf);
|
|
|
|
|
|
|
|
// Allocate buffer (Global header) + (JSON chunk header) + (JSON chunk) + (Binary chunk header) + (Binary chunk)
|
|
|
|
var glbLength = 12 + 8 + jsonBuffer.length + 8 + binaryBuffer.length;
|
|
|
|
var glb = Buffer.alloc(glbLength);
|
|
|
|
|
|
|
|
// Write binary glTF header (magic, version, length)
|
|
|
|
var byteOffset = 0;
|
|
|
|
glb.writeUInt32LE(0x46546C67, byteOffset);
|
|
|
|
byteOffset += 4;
|
|
|
|
glb.writeUInt32LE(2, byteOffset);
|
|
|
|
byteOffset += 4;
|
|
|
|
glb.writeUInt32LE(glbLength, byteOffset);
|
|
|
|
byteOffset += 4;
|
|
|
|
|
|
|
|
// Write JSON Chunk header (length, type)
|
|
|
|
glb.writeUInt32LE(jsonBuffer.length, byteOffset);
|
|
|
|
byteOffset += 4;
|
|
|
|
glb.writeUInt32LE(0x4E4F534A, byteOffset); // JSON
|
|
|
|
byteOffset += 4;
|
|
|
|
|
|
|
|
// Write JSON Chunk
|
|
|
|
jsonBuffer.copy(glb, byteOffset);
|
|
|
|
byteOffset += jsonBuffer.length;
|
|
|
|
|
|
|
|
// Write Binary Chunk header (length, type)
|
|
|
|
glb.writeUInt32LE(binaryBuffer.length, byteOffset);
|
|
|
|
byteOffset += 4;
|
|
|
|
glb.writeUInt32LE(0x004E4942, byteOffset); // BIN
|
|
|
|
byteOffset += 4;
|
|
|
|
|
|
|
|
// Write Binary Chunk
|
|
|
|
binaryBuffer.copy(glb, byteOffset);
|
|
|
|
return glb;
|
|
|
|
}
|