GLTFExporter.js 12.2 KB
Newer Older
F
Fernando Serrano 已提交
1 2 3 4 5
/**
 * @author fernandojsg / http://fernandojsg.com
 */


F
Fernando Serrano 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// @TODO Should be accessible from the renderer itself instead of duplicating it here
function paramThreeToGL( p ) {

	var extension;

	if ( p === THREE.RepeatWrapping ) return WebGLConstants.REPEAT;
	if ( p === THREE.ClampToEdgeWrapping ) return WebGLConstants.CLAMP_TO_EDGE;
	if ( p === THREE.MirroredRepeatWrapping ) return WebGLConstants.MIRRORED_REPEAT;

	if ( p === THREE.NearestFilter ) return WebGLConstants.NEAREST;
	if ( p === THREE.NearestMipMapNearestFilter ) return WebGLConstants.NEAREST_MIPMAP_NEAREST;
	if ( p === THREE.NearestMipMapLinearFilter ) return WebGLConstants.NEAREST_MIPMAP_LINEAR;

	if ( p === THREE.LinearFilter ) return WebGLConstants.LINEAR;
	if ( p === THREE.LinearMipMapNearestFilter ) return WebGLConstants.LINEAR_MIPMAP_NEAREST;
	if ( p === THREE.LinearMipMapLinearFilter ) return WebGLConstants.LINEAR_MIPMAP_LINEAR;
	return 0;
}

// @TODO Move it to constants.js ?
var WebGLConstants = {
	ARRAY_BUFFER: 0x8892,
	ELEMENT_ARRAY_BUFFER: 0x8893,

	BYTE: 0x1400,
	UNSIGNED_BYTE: 0x1401,
	SHORT: 0x1402,
	UNSIGNED_SHORT: 0x1403,
	INT: 0x1404,
	UNSIGNED_INT: 0x1405,
	FLOAT: 0x1406,

	NEAREST: 0x2600,
	LINEAR: 0x2601,
	NEAREST_MIPMAP_NEAREST: 0x2700,
	LINEAR_MIPMAP_NEAREST: 0x2701,
	NEAREST_MIPMAP_LINEAR: 0x2702,
	LINEAR_MIPMAP_LINEAR: 0x2703,

	REPEAT: 0x2901,
	CLAMP_TO_EDGE: 0x812F,
	MIRRORED_REPEAT: 0x8370,
};
F
Fernando Serrano 已提交
49

F
Fernando Serrano 已提交
50 51 52
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
F
Fernando Serrano 已提交
53 54 55 56 57
THREE.GLTFExporter = function () {};

THREE.GLTFExporter.prototype = {

	constructor: THREE.GLTFExporter,
F
Fernando Serrano 已提交
58 59 60

	parse: function ( input, options, onDone ) {
		options = options || {};
F
Fernando Serrano 已提交
61 62

		var outputJSON = {
F
Fernando Serrano 已提交
63 64 65 66 67
			asset: {
				version: "2.0",
				generator: "THREE.JS GLTFExporter" // @QUESTION Does it support spaces?
		 	}
      // extensionsUsed : ['KHR_materials_common'],
F
Fernando Serrano 已提交
68 69 70 71
    };

		var byteOffset = 0;
		var dataViews = [];
F
Fernando Serrano 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
		
		/**
		 * Get the min and he max vectors from the given attribute
		 * @param  {THREE.WebGLAttribute} attribute Attribute to find the min/max
		 * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
		 */
		function getMinMax ( attribute ) {
			var output = {
				min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
				max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
			};

			for ( var i = 0; i < attribute.count; i++ ) {
				for (var a = 0; a < attribute.itemSize; a++ ) {
					var value = attribute.array[i * attribute.itemSize + a];
					output.min[ a ] = Math.min( output.min[ a ], value );
					output.max[ a ] = Math.max( output.max[ a ], value );
				}
			}

			return output;
		}
F
Fernando Serrano 已提交
94 95

		/**
F
Fernando Serrano 已提交
96 97 98 99
		 * Process a buffer to append to the default one.
		 * @param  {THREE.BufferAttribute} attribute     Attribute to store
		 * @param  {Integer} componentType Component type (Unsigned short, unsigned int or float)
		 * @return {Integer}               Index of the buffer created (Currently always 0)
F
Fernando Serrano 已提交
100 101 102 103 104 105 106 107 108 109 110
		 */
		function processBuffer ( attribute, componentType ) {
			if (!outputJSON.buffers) {
				outputJSON.buffers = [
					{
						byteLength: 0,
						uri: ''
					}
				];
			}

F
Fernando Serrano 已提交
111
			// Create a new dataview and dump the attribute's array into it
F
Fernando Serrano 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
			var dataView = new DataView( new ArrayBuffer( attribute.array.byteLength ) );

			var offset = 0;
			var offsetInc = componentType === WebGLConstants.UNSIGNED_SHORT ? 2 : 4;

			for ( var i = 0; i < attribute.count; i++ ) {
				for (var a = 0; a < attribute.itemSize; a++ ) {
					var value = attribute.array[i * attribute.itemSize + a];
					if (componentType === WebGLConstants.FLOAT) {
						dataView.setFloat32(offset, value, true);
					} else if (componentType === WebGLConstants.UNSIGNED_INT) {
						dataView.setUint8(offset, value, true);
					} else if (componentType === WebGLConstants.UNSIGNED_SHORT) {
						dataView.setUint16(offset, value, true);
					}
					offset += offsetInc;
				}
			}

F
Fernando Serrano 已提交
131
			// We just use one buffer
F
Fernando Serrano 已提交
132 133 134 135 136 137
			dataViews.push(dataView);

			return 0;
		}

		/**
F
Fernando Serrano 已提交
138
		 * Process and generate a BufferView
F
Fernando Serrano 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		function processBufferView ( data, componentType ) {
			var isVertexAttributes = componentType === WebGLConstants.FLOAT;
			if (!outputJSON.bufferViews) {
				outputJSON.bufferViews = [];
			}

			var gltfBufferView = {
				buffer: processBuffer( data, componentType ),
				byteOffset: byteOffset,
				byteLength: data.array.byteLength,
				byteStride: data.itemSize * (componentType === WebGLConstants.UNSIGNED_SHORT ? 2 : 4),
				target: isVertexAttributes ? WebGLConstants.ARRAY_BUFFER : WebGLConstants.ELEMENT_ARRAY_BUFFER
			};

			byteOffset += data.array.byteLength;

			outputJSON.bufferViews.push(gltfBufferView);
F
Fernando Serrano 已提交
159 160

			// @TODO Ideally we'll have just two bufferviews: 0 is for vertex attributes, 1 for indices
F
Fernando Serrano 已提交
161 162 163 164 165 166 167 168
			var output = {
				id: outputJSON.bufferViews.length - 1,
				byteLength: 0
			};
			return output;
		}

		/**
F
Fernando Serrano 已提交
169 170 171
		 * Process attribute to generate an accessor
		 * @param  {THREE.WebGLAttribute} attribute Attribute to process
		 * @return {Integer}           Index of the processed accessor on the "accessors" array
F
Fernando Serrano 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184
		 */
		function processAccessor ( attribute ) {
			if (!outputJSON.accessors) {
				outputJSON.accessors = [];
			}

			var types = [
				"SCALAR",
				"VEC2",
				"VEC3",
				"VEC4"
			];

F
Fernando Serrano 已提交
185
			// Detect the component type of the attribute array (float, uint or ushort)
F
Fernando Serrano 已提交
186 187 188 189 190
			var componentType = attribute instanceof THREE.Float32BufferAttribute ? WebGLConstants.FLOAT :
				(attribute instanceof THREE.Uint32BufferAttribute ? WebGLConstants.UNSIGNED_INT : WebGLConstants.UNSIGNED_SHORT);

			var minMax = getMinMax( attribute );
			var bufferView = processBufferView( attribute, componentType );
F
Fernando Serrano 已提交
191

F
Fernando Serrano 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			var gltfAccessor = {
				bufferView: bufferView.id,
				byteOffset: bufferView.byteOffset,
				componentType: componentType,
				count: attribute.count,
				max: minMax.max,
				min: minMax.min,
				type: types[ attribute.itemSize - 1]
			};

			outputJSON.accessors.push( gltfAccessor );

			return outputJSON.accessors.length - 1;
		}

		/**
F
Fernando Serrano 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
		 * Process image
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "images" array
		 */
		function processImage ( map ) {
			if (!outputJSON.images) {
				outputJSON.images = [];
			}

			var gltfImage = {};

			if (options.embedImages) {
				// @TODO { bufferView, mimeType }
			} else {
				// @TODO base64 based on options
				gltfImage.uri = map.image.src;
			}

			outputJSON.images.push( gltfImage );

			return outputJSON.images.length - 1;
		}

		/**
		 * Process sampler
		 * @param  {Texture} map Texture to process
		 * @return {Integer}     Index of the processed texture in the "samplers" array
		 */
		function processSampler ( map ) {
			if (!outputJSON.samplers) {
				outputJSON.samplers = [];
			}

			var gltfSampler = {
				magFilter: paramThreeToGL(map.magFilter),
				minFilter: paramThreeToGL(map.minFilter),
				wrapS: paramThreeToGL(map.wrapS),
				wrapT: paramThreeToGL(map.wrapT)
			};

			outputJSON.samplers.push( gltfSampler );

			return outputJSON.samplers.length - 1;
		}

		/**
		 * Process texture
		 * @param  {Texture} map Map to process
		 * @return {Integer}     Index of the processed texture in the "textures" array
		 */
		function processTexture ( map ) {
			if (!outputJSON.textures) {
				outputJSON.textures = [];
			}

			var gltfTexture = {
				sampler: processSampler(map),
				source: processImage(map)
			};

			outputJSON.textures.push( gltfTexture );

			return outputJSON.textures.length - 1;
		}

		/**
		 * Process material
		 * @param  {THREE.Material} material Material to process
		 * @return {Integer}      Index of the processed material in the "materials" array
F
Fernando Serrano 已提交
277 278
		 */
		function processMaterial ( material ) {
F
Fernando Serrano 已提交
279
			if ( !outputJSON.materials ) {
F
Fernando Serrano 已提交
280 281
				outputJSON.materials = [];
			}
F
Fernando Serrano 已提交
282 283 284 285 286 287

			if ( !material instanceof THREE.MeshStandardMaterial ) {
				throw 'Currently just support THREE.StandardMaterial is supported';
			}

			// @QUESTION Should we avoid including any attribute that has the default value?
F
Fernando Serrano 已提交
288 289
			var gltfMaterial = {
				pbrMetallicRoughness: {
F
Fernando Serrano 已提交
290
					baseColorFactor: material.color.toArray().concat( [ material.opacity ] ),
F
Fernando Serrano 已提交
291 292 293 294 295
					metallicFactor: material.metalness,
					roughnessFactor: material.roughness
				}
			};

F
Fernando Serrano 已提交
296 297 298 299 300 301 302 303
			if ( material.map ) {
				gltfMaterial.pbrMetallicRoughness.baseColorTexture = {
					index: processTexture( material.map ),
					texCoord: 0 // @FIXME
				}
			}

			if ( material.side === THREE.DoubleSide ) {
F
Fernando Serrano 已提交
304 305 306
				gltfMaterial.doubleSided = true;
			}

F
Fernando Serrano 已提交
307
			if ( material.name ) {
F
Fernando Serrano 已提交
308 309 310
				gltfMaterial.name = material.name;
			}

F
Fernando Serrano 已提交
311
			outputJSON.materials.push( gltfMaterial );
F
Fernando Serrano 已提交
312 313 314 315 316

			return outputJSON.materials.length - 1;
		}

		/**
F
Fernando Serrano 已提交
317 318 319
		 * Process mesh
		 * @param  {THREE.Mesh} mesh Mesh to process
		 * @return {Integer}      Index of the processed mesh in the "meshes" array
F
Fernando Serrano 已提交
320 321 322 323 324 325 326
		 */
		function processMesh( mesh ) {
			if ( !outputJSON.meshes ) {
				outputJSON.meshes = [];
			}

			var geometry = mesh.geometry;
F
Fernando Serrano 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339

			var modes = {
				POINTS: 0,
				LINES: 1,
				LINE_LOOP: 2,
				LINE_STRIP: 3,
				TRIANGLES: 4,
				TRIANGLE_STRIP: 5,
				TRIANGLE_FAN: 6
			}

			// @FIXME Select the correct mode based on the mesh
			var mode = modes.TRIANGLES;
F
Fernando Serrano 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

			var gltfMesh = {
				primitives: [
					{
						mode: mode,
						attributes: {},
						material: processMaterial( mesh.material ),
					 	indices: processAccessor( geometry.index )
					}
				]
			};

			var gltfAttributes = gltfMesh.primitives[0].attributes;
			var attributes = geometry.attributes;

F
Fernando Serrano 已提交
355 356 357 358 359 360 361 362
			// Conversion between attributes names in threejs and gltf spec
			var nameConversion = {
				'uv': 'TEXCOORD_0',
				'uv2': 'TEXCOORD_1',
				'color': 'COLOR_0'
			};

			// For every attribute create an accessor
F
Fernando Serrano 已提交
363 364
			for (attributeName in geometry.attributes) {
				var attribute = geometry.attributes[ attributeName ];
F
Fernando Serrano 已提交
365 366
				attributeName = nameConversion[attributeName] || attributeName.toUpperCase()
				gltfAttributes[attributeName] = processAccessor( attribute );
F
Fernando Serrano 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
			}

			// @todo Not really necessary, isn't it?
			if ( geometry.type ) {
				gltfMesh.name = geometry.type;
			}

			outputJSON.meshes.push( gltfMesh );

			return outputJSON.meshes.length - 1;
		}

		/**
		 * Process Object3D node
		 * @param  {THREE.Object3D} node Object3D to processNode
		 * @return {Integer}      Index of the node in the nodes list
		 */
		function processNode ( object ) {

			if (!outputJSON.nodes) {
				outputJSON.nodes = [];
			}

			var gltfNode = {
				matrix: object.matrix.elements
			};

			if ( object.name ) {
				gltfNode.name = object.name;
			}

			if ( object instanceof THREE.Mesh ) {
				gltfNode.mesh = processMesh( object );
F
Fernando Serrano 已提交
400 401
			} else {

F
Fernando Serrano 已提交
402 403 404
			}

			if ( object.children.length > 0 ) {
F
Fernando Serrano 已提交
405
				gltfNode.children = [];
F
Fernando Serrano 已提交
406 407 408 409

				for ( var i = 0, l = object.children.length; i < l; i ++ ) {
					var child = object.children[ i ];
					if ( child instanceof THREE.Mesh ) {
F
Fernando Serrano 已提交
410
						gltfNode.children.push( processNode( child ) );
F
Fernando Serrano 已提交
411 412 413 414 415 416 417 418 419 420
					}
				}
			}

			outputJSON.nodes.push( gltfNode );

			return outputJSON.nodes.length - 1;
		}

		/**
F
Fernando Serrano 已提交
421
		 * Process Scene
F
Fernando Serrano 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
		 * @param  {THREE.Scene} node Scene to process
		 */
		function processScene( scene ) {
			if (!outputJSON.scene) {
				outputJSON.scenes = [];
				outputJSON.scene = 0;
			}

			var gltfScene = {
				nodes: []
			};

			if ( scene.name ) {
				gltfScene.name = scene.name;
			}

			outputJSON.scenes.push(gltfScene);

			for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
F
Fernando Serrano 已提交
441 442 443 444 445 446
				var child = scene.children[ i ];

				// @TODO Right now we just process meshes
				if ( child instanceof THREE.Mesh ) {
					gltfScene.nodes.push( processNode( child ) );
				}
F
Fernando Serrano 已提交
447 448 449
			}
		}

F
Fernando Serrano 已提交
450 451 452 453 454 455 456 457
		// Process the scene/s
		if ( input instanceof Array ) {
			for ( i = 0; i < input.length; i++ ) {
				processScene( input[ i ] );
			}
		} else {
			processScene( input );
		}
F
Fernando Serrano 已提交
458

F
Fernando Serrano 已提交
459
		// Generate buffer
F
Fernando Serrano 已提交
460 461 462 463 464 465 466 467 468 469
		var blob = new Blob(dataViews, {type: 'application/octet-binary'});
		outputJSON.buffers[0].byteLength = blob.size;
		objectURL = URL.createObjectURL(blob);

		var reader = new window.FileReader();
		 reader.readAsDataURL(blob);
		 reader.onloadend = function() {
			 base64data = reader.result;
			 outputJSON.buffers[0].uri = base64data;
			 console.log(JSON.stringify(outputJSON, null, 2));
F
Fernando Serrano 已提交
470
			 onDone(outputJSON);
F
Fernando Serrano 已提交
471 472 473
		 }
	}
};