WebGLRenderer.js 82.2 KB
Newer Older
M
Mr.doob 已提交
1 2 3 4 5 6 7 8 9
/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

THREE.WebGLRenderer = function ( parameters ) {

10
	console.log( 'THREE.WebGLRenderer', THREE.REVISION );
M
Mr.doob 已提交
11 12 13 14

	parameters = parameters || {};

	var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
15
	_context = parameters.context !== undefined ? parameters.context : null,
M
Mr.doob 已提交
16

M
Mr.doob 已提交
17 18
	_width = _canvas.width,
	_height = _canvas.height,
19

20 21
	pixelRatio = 1,

22
	_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
23
	_depth = parameters.depth !== undefined ? parameters.depth : true,
M
Mr.doob 已提交
24
	_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
25 26
	_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
	_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
M
Mr.doob 已提交
27 28
	_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,

29 30
	_clearColor = new THREE.Color( 0x000000 ),
	_clearAlpha = 0;
M
Mr.doob 已提交
31

M
Mr.doob 已提交
32
	var lights = [];
M
Mr.doob 已提交
33

O
OpenShift guest 已提交
34
	var opaqueObjects = [];
M
Mr.doob 已提交
35
	var opaqueObjectsLastIndex = - 1;
36
	var transparentObjects = [];
M
Mr.doob 已提交
37
	var transparentObjectsLastIndex = - 1;
38

39 40
	var morphInfluences = new Float32Array( 8 );

41

M
Mr.doob 已提交
42 43 44
	var sprites = [];
	var lensFlares = [];

M
Mr.doob 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	// public properties

	this.domElement = _canvas;
	this.context = null;

	// clearing

	this.autoClear = true;
	this.autoClearColor = true;
	this.autoClearDepth = true;
	this.autoClearStencil = true;

	// scene graph

	this.sortObjects = true;

	// physically based shading

63
	this.gammaFactor = 2.0;	// for backwards compatibility
M
Mr.doob 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
	this.gammaInput = false;
	this.gammaOutput = false;

	// morphs

	this.maxMorphTargets = 8;
	this.maxMorphNormals = 4;

	// flags

	this.autoScaleCubemaps = true;

	// internal properties

	var _this = this,

	// internal state cache

	_currentProgram = null,
	_currentFramebuffer = null,
84
	_currentMaterialId = - 1,
85
	_currentGeometryProgram = '',
M
Mr.doob 已提交
86 87 88 89 90 91
	_currentCamera = null,

	_usedTextureUnits = 0,

	_viewportX = 0,
	_viewportY = 0,
92 93
	_viewportWidth = _canvas.width,
	_viewportHeight = _canvas.height,
M
Mr.doob 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	_currentWidth = 0,
	_currentHeight = 0,

	// frustum

	_frustum = new THREE.Frustum(),

	 // camera matrices cache

	_projScreenMatrix = new THREE.Matrix4(),

	_vector3 = new THREE.Vector3(),

	// light arrays cache

	_direction = new THREE.Vector3(),

	_lightsNeedUpdate = true,

	_lights = {

		ambient: [ 0, 0, 0 ],
G
gero3 已提交
116
		directional: { length: 0, colors: [], positions: [] },
M
Mr.doob 已提交
117 118
		point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
		spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
G
gero3 已提交
119
		hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
M
Mr.doob 已提交
120

121 122
	},

M
Mr.doob 已提交
123 124
	// info

125
	_infoMemory = {
126 127

		geometries: 0,
T
tschw 已提交
128
		textures: 0
129 130 131

	},

132
	_infoRender = {
133 134 135 136 137 138

		calls: 0,
		vertices: 0,
		faces: 0,
		points: 0

M
Mr.doob 已提交
139 140
	};

M
Mr.doob 已提交
141
	this.info = {
142

M
Mr.doob 已提交
143 144
		render: _infoRender,
		memory: _infoMemory,
145
		programs: null
M
Mr.doob 已提交
146 147

	};
148

149

M
Mr.doob 已提交
150 151 152 153
	// initialize

	var _gl;

M
Mr.doob 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	try {

		var attributes = {
			alpha: _alpha,
			depth: _depth,
			stencil: _stencil,
			antialias: _antialias,
			premultipliedAlpha: _premultipliedAlpha,
			preserveDrawingBuffer: _preserveDrawingBuffer
		};

		_gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );

		if ( _gl === null ) {

G
gero3 已提交
169
			if ( _canvas.getContext( 'webgl' ) !== null ) {
170 171 172 173 174 175 176 177

				throw 'Error creating WebGL context with your selected attributes.';

			} else {

				throw 'Error creating WebGL context.';

			}
M
Mr.doob 已提交
178 179 180

		}

D
dubejf 已提交
181
		_canvas.addEventListener( 'webglcontextlost', onContextLost, false );
182

M
Mr.doob 已提交
183 184
	} catch ( error ) {

185
		console.error( 'THREE.WebGLRenderer: ' + error );
M
Mr.doob 已提交
186 187 188

	}

189 190
	var extensions = new THREE.WebGLExtensions( _gl );

191 192
	extensions.get( 'OES_texture_float' );
	extensions.get( 'OES_texture_float_linear' );
193 194
	extensions.get( 'OES_texture_half_float' );
	extensions.get( 'OES_texture_half_float_linear' );
195
	extensions.get( 'OES_standard_derivatives' );
B
Ben Adams 已提交
196
	extensions.get( 'ANGLE_instanced_arrays' );
197

198 199
	if ( extensions.get( 'OES_element_index_uint' ) ) {

200
		THREE.BufferGeometry.MaxIndex = 4294967296;
201 202 203

	}

M
Mr.doob 已提交
204
	var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
M
Mr.doob 已提交
205

206 207 208
	var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
	var properties = new THREE.WebGLProperties();
	var objects = new THREE.WebGLObjects( _gl, properties, this.info );
G
gero3 已提交
209
	var programCache = new THREE.WebGLPrograms( this, capabilities );
210

211 212
	this.info.programs = programCache.programs;

213 214
	var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
	var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
215

M
Mr.doob 已提交
216 217
	//

218
	function glClearColor( r, g, b, a ) {
219 220 221

		if ( _premultipliedAlpha === true ) {

222
			r *= a; g *= a; b *= a;
223 224 225

		}

226 227
		_gl.clearColor( r, g, b, a );

228
	}
229

230
	function setDefaultGLState() {
M
Mr.doob 已提交
231

M
Mr.doob 已提交
232
		state.init();
M
Mr.doob 已提交
233 234 235

		_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );

236
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
237

238
	}
239

240
	function resetGLState() {
241 242 243 244

		_currentProgram = null;
		_currentCamera = null;

245
		_currentGeometryProgram = '';
246 247 248 249
		_currentMaterialId = - 1;

		_lightsNeedUpdate = true;

M
Mr.doob 已提交
250 251
		state.reset();

252
	}
M
Mr.doob 已提交
253 254 255 256

	setDefaultGLState();

	this.context = _gl;
M
Mr.doob 已提交
257
	this.capabilities = capabilities;
258
	this.extensions = extensions;
M
Mr.doob 已提交
259
	this.state = state;
M
Mr.doob 已提交
260

M
Mr.doob 已提交
261 262
	// shadow map

M
Mr.doob 已提交
263
	var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
M
Mr.doob 已提交
264

265
	this.shadowMap = shadowMap;
M
Mr.doob 已提交
266

M
Mr.doob 已提交
267

M
Mr.doob 已提交
268 269 270 271 272
	// Plugins

	var spritePlugin = new THREE.SpritePlugin( this, sprites );
	var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );

M
Mr.doob 已提交
273 274 275 276 277 278 279 280
	// API

	this.getContext = function () {

		return _gl;

	};

281 282 283 284 285 286
	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

287 288 289 290 291 292
	this.forceContextLoss = function () {

		extensions.get( 'WEBGL_lose_context' ).loseContext();

	};

293
	this.getMaxAnisotropy = ( function () {
M
Mr.doob 已提交
294

295
		var value;
M
Mr.doob 已提交
296

297
		return function getMaxAnisotropy() {
298

M
Mr.doob 已提交
299
			if ( value !== undefined ) return value;
300

M
Mr.doob 已提交
301
			var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
302

M
Mr.doob 已提交
303
			if ( extension !== null ) {
304

M
Mr.doob 已提交
305
				value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
306

M
Mr.doob 已提交
307 308 309 310 311
			} else {

				value = 0;

			}
312 313 314 315 316 317

			return value;

		}

	} )();
M
Mr.doob 已提交
318 319 320

	this.getPrecision = function () {

G
gero3 已提交
321
		return capabilities.precision;
M
Mr.doob 已提交
322 323 324

	};

325 326 327 328 329 330 331 332
	this.getPixelRatio = function () {

		return pixelRatio;

	};

	this.setPixelRatio = function ( value ) {

333
		if ( value !== undefined ) pixelRatio = value;
334 335 336

	};

337 338 339 340 341 342 343 344 345
	this.getSize = function () {

		return {
			width: _width,
			height: _height
		};

	};

346
	this.setSize = function ( width, height, updateStyle ) {
M
Mr.doob 已提交
347

348 349 350
		_width = width;
		_height = height;

351 352
		_canvas.width = width * pixelRatio;
		_canvas.height = height * pixelRatio;
353

354
		if ( updateStyle !== false ) {
355

G
gero3 已提交
356 357
			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';
358

G
gero3 已提交
359
		}
M
Mr.doob 已提交
360

361
		this.setViewport( 0, 0, width, height );
M
Mr.doob 已提交
362 363 364 365 366

	};

	this.setViewport = function ( x, y, width, height ) {

367 368
		_viewportX = x * pixelRatio;
		_viewportY = y * pixelRatio;
M
Mr.doob 已提交
369

370 371
		_viewportWidth = width * pixelRatio;
		_viewportHeight = height * pixelRatio;
M
Mr.doob 已提交
372 373 374 375 376

		_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );

	};

M
Mr.doob 已提交
377 378 379 380 381 382 383 384 385 386
	this.getViewport = function ( dimensions ) {

		dimensions.x = _viewportX / pixelRatio;
		dimensions.y = _viewportY / pixelRatio;

		dimensions.z = _viewportWidth / pixelRatio;
		dimensions.w = _viewportHeight / pixelRatio;

	};

M
Mr.doob 已提交
387 388
	this.setScissor = function ( x, y, width, height ) {

389
		_gl.scissor(
390 391 392 393
			x * pixelRatio,
			y * pixelRatio,
			width * pixelRatio,
			height * pixelRatio
394
		);
M
Mr.doob 已提交
395 396 397

	};

398
	this.enableScissorTest = function ( boolean ) {
M
Mr.doob 已提交
399

M
Mr.doob 已提交
400
		state.setScissorTest( boolean );
M
Mr.doob 已提交
401 402 403 404 405

	};

	// Clearing

M
Mr.doob 已提交
406
	this.getClearColor = function () {
M
Mr.doob 已提交
407

M
Mr.doob 已提交
408
		return _clearColor;
M
Mr.doob 已提交
409 410 411

	};

M
Mr.doob 已提交
412
	this.setClearColor = function ( color, alpha ) {
M
Mr.doob 已提交
413

M
Mr.doob 已提交
414
		_clearColor.set( color );
415

M
Mr.doob 已提交
416
		_clearAlpha = alpha !== undefined ? alpha : 1;
M
Mr.doob 已提交
417

418
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
419 420 421

	};

M
Mr.doob 已提交
422
	this.getClearAlpha = function () {
M
Mr.doob 已提交
423

M
Mr.doob 已提交
424
		return _clearAlpha;
M
Mr.doob 已提交
425 426 427

	};

M
Mr.doob 已提交
428
	this.setClearAlpha = function ( alpha ) {
M
Mr.doob 已提交
429

M
Mr.doob 已提交
430
		_clearAlpha = alpha;
M
Mr.doob 已提交
431

432
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
433 434 435 436 437 438 439 440 441 442 443 444

	};

	this.clear = function ( color, depth, stencil ) {

		var bits = 0;

		if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
		if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
		if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;

		_gl.clear( bits );
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

	};

	this.clearColor = function () {

		_gl.clear( _gl.COLOR_BUFFER_BIT );

	};

	this.clearDepth = function () {

		_gl.clear( _gl.DEPTH_BUFFER_BIT );

	};

	this.clearStencil = function () {

		_gl.clear( _gl.STENCIL_BUFFER_BIT );
M
Mr.doob 已提交
463 464 465 466 467 468 469 470 471 472

	};

	this.clearTarget = function ( renderTarget, color, depth, stencil ) {

		this.setRenderTarget( renderTarget );
		this.clear( color, depth, stencil );

	};

M
Mr.doob 已提交
473 474
	// Reset

475
	this.resetGLState = resetGLState;
M
Mr.doob 已提交
476

D
dubejf 已提交
477 478 479 480 481 482
	this.dispose = function() {

		_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );

	};

M
Mr.doob 已提交
483
	// Events
M
Mr.doob 已提交
484

D
dubejf 已提交
485 486 487 488 489 490 491 492 493 494 495
	function onContextLost( event ) {

		event.preventDefault();

		resetGLState();
		setDefaultGLState();

		properties.clear();

	};

496
	function onTextureDispose( event ) {
M
Mr.doob 已提交
497 498 499 500 501 502 503

		var texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

504
		_infoMemory.textures --;
M
Mr.doob 已提交
505 506


507
	}
M
Mr.doob 已提交
508

509
	function onRenderTargetDispose( event ) {
M
Mr.doob 已提交
510 511 512 513 514 515 516

		var renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

517
		_infoMemory.textures --;
M
Mr.doob 已提交
518

519
	}
M
Mr.doob 已提交
520

521
	function onMaterialDispose( event ) {
M
Mr.doob 已提交
522 523 524 525 526 527 528

		var material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

529
	}
M
Mr.doob 已提交
530 531 532

	// Buffer deallocation

533
	function deallocateTexture( texture ) {
M
Mr.doob 已提交
534

535
		var textureProperties = properties.get( texture );
M
Mr.doob 已提交
536

537
		if ( texture.image && textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
538 539 540

			// cube texture

541
			_gl.deleteTexture( textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
542

543 544 545 546
		} else {

			// 2D texture

547
			if ( textureProperties.__webglInit === undefined ) return;
548

549
			_gl.deleteTexture( textureProperties.__webglTexture );
550

M
Mr.doob 已提交
551 552
		}

553
		// remove all webgl properties
554
		properties.delete( texture );
555

556
	}
M
Mr.doob 已提交
557

558
	function deallocateRenderTarget( renderTarget ) {
M
Mr.doob 已提交
559

560
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
561
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
562

M
Mr.doob 已提交
563
		if ( ! renderTarget || textureProperties.__webglTexture === undefined ) return;
M
Mr.doob 已提交
564

M
Mr.doob 已提交
565
		_gl.deleteTexture( textureProperties.__webglTexture );
M
Mr.doob 已提交
566

M
Mr.doob 已提交
567 568 569 570
		if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

			for ( var i = 0; i < 6; i ++ ) {

571 572
				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
				_gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer[ i ] );
M
Mr.doob 已提交
573 574 575 576 577

			}

		} else {

578 579
			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
			_gl.deleteRenderbuffer( renderTargetProperties.__webglRenderbuffer );
M
Mr.doob 已提交
580 581 582

		}

M
Mr.doob 已提交
583
		properties.delete( renderTarget.texture );
D
Daosheng Mu 已提交
584
		properties.delete( renderTarget );
M
Mr.doob 已提交
585

586
	}
M
Mr.doob 已提交
587

588
	function deallocateMaterial( material ) {
M
Mr.doob 已提交
589

590 591 592 593
		releaseMaterialProgramReference( material );

		properties.delete( material );

594
	}
595 596


597
	function releaseMaterialProgramReference( material ) {
598

599
		var programInfo = properties.get( material ).program;
M
Mr.doob 已提交
600 601 602

		material.program = undefined;

603
		if ( programInfo !== undefined ) {
M
Mr.doob 已提交
604

605
			programCache.releaseProgram( programInfo );
M
Mr.doob 已提交
606

M
Mr.doob 已提交
607 608
		}

609
	}
M
Mr.doob 已提交
610 611 612 613 614

	// Buffer rendering

	this.renderBufferImmediate = function ( object, program, material ) {

615
		state.initAttributes();
616

617
		var buffers = properties.get( object );
618

619 620 621 622
		if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
		if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
		if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
		if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
M
Mr.doob 已提交
623

624
		var attributes = program.getAttributes();
625

M
Mr.doob 已提交
626 627
		if ( object.hasPositions ) {

628
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
M
Mr.doob 已提交
629
			_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
630

631 632
			state.enableAttribute( attributes.position );
			_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
633 634 635 636 637

		}

		if ( object.hasNormals ) {

638
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
M
Mr.doob 已提交
639

640
			if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
M
Mr.doob 已提交
641

642
				for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
M
Mr.doob 已提交
643

644
					var array = object.normalArray;
M
Mr.doob 已提交
645

646 647 648
					var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
					var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
					var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
M
Mr.doob 已提交
649

650 651 652
					array[ i + 0 ] = nx;
					array[ i + 1 ] = ny;
					array[ i + 2 ] = nz;
M
Mr.doob 已提交
653

654 655 656
					array[ i + 3 ] = nx;
					array[ i + 4 ] = ny;
					array[ i + 5 ] = nz;
M
Mr.doob 已提交
657

658 659 660
					array[ i + 6 ] = nx;
					array[ i + 7 ] = ny;
					array[ i + 8 ] = nz;
M
Mr.doob 已提交
661 662 663 664 665 666

				}

			}

			_gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
667

668
			state.enableAttribute( attributes.normal );
669

670
			_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
671 672 673 674 675

		}

		if ( object.hasUvs && material.map ) {

676
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
M
Mr.doob 已提交
677
			_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
678

679
			state.enableAttribute( attributes.uv );
680

681
			_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
682 683 684 685 686

		}

		if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {

687
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
M
Mr.doob 已提交
688
			_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
689

690
			state.enableAttribute( attributes.color );
691

692
			_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
693 694 695

		}

696
		state.disableUnusedAttributes();
697

M
Mr.doob 已提交
698 699 700 701 702 703
		_gl.drawArrays( _gl.TRIANGLES, 0, object.count );

		object.count = 0;

	};

704 705
	this.renderBufferDirect = function ( camera, lights, fog, geometry, material, object, group ) {

M
Mr.doob 已提交
706 707 708 709
		setMaterial( material );

		var program = setProgram( camera, lights, fog, material, object );

M
Mr.doob 已提交
710 711
		var updateBuffers = false;
		var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
M
Mr.doob 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742

		if ( geometryProgram !== _currentGeometryProgram ) {

			_currentGeometryProgram = geometryProgram;
			updateBuffers = true;

		}

		// morph targets

		var morphTargetInfluences = object.morphTargetInfluences;

		if ( morphTargetInfluences !== undefined ) {

			var activeInfluences = [];

			for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {

				var influence = morphTargetInfluences[ i ];
				activeInfluences.push( [ influence, i ] );

			}

			activeInfluences.sort( numericalSort );

			if ( activeInfluences.length > 8 ) {

				activeInfluences.length = 8;

			}

743 744
			var morphAttributes = geometry.morphAttributes;

M
Mr.doob 已提交
745 746 747 748 749 750 751
			for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {

				var influence = activeInfluences[ i ];
				morphInfluences[ i ] = influence[ 0 ];

				if ( influence[ 0 ] !== 0 ) {

752
					var index = influence[ 1 ];
M
Mr.doob 已提交
753

754 755
					if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
					if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
M
Mr.doob 已提交
756 757 758

				} else {

759 760
					if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
					if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
M
Mr.doob 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777

				}

			}

			var uniforms = program.getUniforms();

			if ( uniforms.morphTargetInfluences !== null ) {

				_gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );

			}

			updateBuffers = true;

		}

M
Mr.doob 已提交
778 779
		//

780
		var index = geometry.index;
781 782
		var position = geometry.attributes.position;

783 784
		if ( material.wireframe === true ) {

785
			index = objects.getWireframeAttribute( geometry );
786 787 788

		}

789 790
		var renderer;

791
		if ( index !== null ) {
792

793 794
			renderer = indexedBufferRenderer;
			renderer.setIndex( index );
795

796
		} else {
797

798
			renderer = bufferRenderer;
799

800
		}
M
Mr.doob 已提交
801

802
		if ( updateBuffers ) {
M
Mr.doob 已提交
803

804
			setupVertexAttributes( material, program, geometry );
M
Mr.doob 已提交
805

806
			if ( index !== null ) {
807

808
				_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
809 810 811

			}

812
		}
813

M
Mr.doob 已提交
814
		//
815

M
Mr.doob 已提交
816 817
		var dataStart = 0;
		var dataCount = Infinity;
818

M
Mr.doob 已提交
819
		if ( index !== null ) {
820

M
Mr.doob 已提交
821
			dataCount = index.count
822

M
Mr.doob 已提交
823
		} else if ( position !== undefined ) {
824

M
Mr.doob 已提交
825
			dataCount = position.count;
826

M
Mr.doob 已提交
827
		}
828

M
Mr.doob 已提交
829 830
		var rangeStart = geometry.drawRange.start;
		var rangeCount = geometry.drawRange.count;
831

M
Mr.doob 已提交
832 833
		var groupStart = group !== null ? group.start : 0;
		var groupCount = group !== null ? group.count : Infinity;
834

M
Mr.doob 已提交
835 836 837 838 839 840
		var drawStart = Math.max( dataStart, rangeStart, groupStart );
		var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;

		var drawCount = Math.max( 0, drawEnd - drawStart + 1 );

		//
841

842
		if ( object instanceof THREE.Mesh ) {
843

844
			if ( material.wireframe === true ) {
845

846 847
				state.setLineWidth( material.wireframeLinewidth * pixelRatio );
				renderer.setMode( _gl.LINES );
848

849
			} else {
850

851
				renderer.setMode( _gl.TRIANGLES );
852

853
			}
854

855
			if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
856

857
				renderer.renderInstances( geometry );
858

859
			} else {
860

M
Mr.doob 已提交
861
				renderer.render( drawStart, drawCount );
862

863
			}
864

865
		} else if ( object instanceof THREE.Line ) {
866

867
			var lineWidth = material.linewidth;
868

869
			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
870

871
			state.setLineWidth( lineWidth * pixelRatio );
872

873
			if ( object instanceof THREE.LineSegments ) {
874

875
				renderer.setMode( _gl.LINES );
876

877
			} else {
878

879
				renderer.setMode( _gl.LINE_STRIP );
880 881

			}
M
Mr.doob 已提交
882

M
Mr.doob 已提交
883
			renderer.render( drawStart, drawCount );
884

885
		} else if ( object instanceof THREE.Points ) {
886 887

			renderer.setMode( _gl.POINTS );
M
Mr.doob 已提交
888
			renderer.render( drawStart, drawCount );
889

M
Mr.doob 已提交
890 891 892 893
		}

	};

894
	function setupVertexAttributes( material, program, geometry, startIndex ) {
M
Mr.doob 已提交
895

M
Mr.doob 已提交
896
		var extension;
B
Ben Adams 已提交
897

M
Mr.doob 已提交
898
		if ( geometry instanceof THREE.InstancedBufferGeometry ) {
B
Ben Adams 已提交
899

M
Mr.doob 已提交
900
			extension = extensions.get( 'ANGLE_instanced_arrays' );
B
Ben Adams 已提交
901

M
Mr.doob 已提交
902
			if ( extension === null ) {
B
Ben Adams 已提交
903

904
				console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
M
Mr.doob 已提交
905
				return;
B
Ben Adams 已提交
906

M
Mr.doob 已提交
907 908 909
			}

		}
B
Ben Adams 已提交
910

911 912
		if ( startIndex === undefined ) startIndex = 0;

913 914
		state.initAttributes();

915
		var geometryAttributes = geometry.attributes;
916

917
		var programAttributes = program.getAttributes();
918

919
		var materialDefaultAttributeValues = material.defaultAttributeValues;
920

921
		for ( var name in programAttributes ) {
922

923
			var programAttribute = programAttributes[ name ];
M
Mr.doob 已提交
924

M
Mr.doob 已提交
925
			if ( programAttribute >= 0 ) {
M
Mr.doob 已提交
926

927
				var geometryAttribute = geometryAttributes[ name ];
928

M
Mr.doob 已提交
929
				if ( geometryAttribute !== undefined ) {
M
Mr.doob 已提交
930

931
					var size = geometryAttribute.itemSize;
G
gero3 已提交
932
					var buffer = objects.getAttributeBuffer( geometryAttribute );
933

B
Ben Adams 已提交
934
					if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
935

M
Mr.doob 已提交
936 937 938 939 940
						var data = geometryAttribute.data;
						var stride = data.stride;
						var offset = geometryAttribute.offset;

						if ( data instanceof THREE.InstancedInterleavedBuffer ) {
M
Mr.doob 已提交
941

M
Mr.doob 已提交
942
							state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
B
Ben Adams 已提交
943

M
Mr.doob 已提交
944
							if ( geometry.maxInstancedCount === undefined ) {
945

D
dubejf 已提交
946
								geometry.maxInstancedCount = data.meshPerAttribute * data.count;
B
Ben Adams 已提交
947

M
Mr.doob 已提交
948
							}
B
Ben Adams 已提交
949

M
Mr.doob 已提交
950
						} else {
B
Ben Adams 已提交
951

M
Mr.doob 已提交
952
							state.enableAttribute( programAttribute );
B
Ben Adams 已提交
953

M
Mr.doob 已提交
954
						}
B
Ben Adams 已提交
955

M
Mr.doob 已提交
956 957
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
						_gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
B
Ben Adams 已提交
958

M
Mr.doob 已提交
959
					} else {
B
Ben Adams 已提交
960

M
Mr.doob 已提交
961
						if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
B
Ben Adams 已提交
962

M
Mr.doob 已提交
963
							state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
B
Ben Adams 已提交
964

M
Mr.doob 已提交
965
							if ( geometry.maxInstancedCount === undefined ) {
B
Ben Adams 已提交
966

D
dubejf 已提交
967
								geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
B
Ben Adams 已提交
968

M
Mr.doob 已提交
969
							}
B
Ben Adams 已提交
970

M
Mr.doob 已提交
971 972 973 974
						} else {

							state.enableAttribute( programAttribute );

M
Mr.doob 已提交
975
						}
B
Ben Adams 已提交
976

M
Mr.doob 已提交
977 978 979
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
						_gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32

B
Ben Adams 已提交
980
					}
M
Mr.doob 已提交
981

982 983
				} else if ( materialDefaultAttributeValues !== undefined ) {

T
tschw 已提交
984
					var value = materialDefaultAttributeValues[ name ];
985

986
					if ( value !== undefined ) {
M
Mr.doob 已提交
987

988
						switch ( value.length ) {
M
Mr.doob 已提交
989

990 991 992
							case 2:
								_gl.vertexAttrib2fv( programAttribute, value );
								break;
M
Mr.doob 已提交
993

994 995 996
							case 3:
								_gl.vertexAttrib3fv( programAttribute, value );
								break;
M
Mr.doob 已提交
997

998 999 1000
							case 4:
								_gl.vertexAttrib4fv( programAttribute, value );
								break;
1001

1002 1003
							default:
								_gl.vertexAttrib1fv( programAttribute, value );
1004 1005

						}
M
Mr.doob 已提交
1006 1007 1008 1009 1010 1011 1012 1013

					}

				}

			}

		}
1014

1015
		state.disableUnusedAttributes();
1016

M
Mr.doob 已提交
1017 1018
	}

M
Mr.doob 已提交
1019 1020
	// Sorting

1021 1022 1023 1024 1025 1026
	function numericalSort ( a, b ) {

		return b[ 0 ] - a[ 0 ];

	}

M
Mr.doob 已提交
1027 1028
	function painterSortStable ( a, b ) {

U
unconed 已提交
1029
		if ( a.object.renderOrder !== b.object.renderOrder ) {
1030

U
unconed 已提交
1031
			return a.object.renderOrder - b.object.renderOrder;
1032

M
Mr.doob 已提交
1033
		} else if ( a.material.id !== b.material.id ) {
M
Mr.doob 已提交
1034

M
Mr.doob 已提交
1035
			return a.material.id - b.material.id;
1036 1037

		} else if ( a.z !== b.z ) {
M
Mr.doob 已提交
1038

M
Mr.doob 已提交
1039
			return a.z - b.z;
M
Mr.doob 已提交
1040 1041 1042

		} else {

1043
			return a.id - b.id;
M
Mr.doob 已提交
1044 1045 1046

		}

1047
	}
M
Mr.doob 已提交
1048

1049 1050
	function reversePainterSortStable ( a, b ) {

U
unconed 已提交
1051
		if ( a.object.renderOrder !== b.object.renderOrder ) {
1052

U
unconed 已提交
1053
			return a.object.renderOrder - b.object.renderOrder;
1054 1055

		} if ( a.z !== b.z ) {
1056

M
Mr.doob 已提交
1057
			return b.z - a.z;
1058 1059 1060 1061 1062 1063 1064

		} else {

			return a.id - b.id;

		}

1065
	}
1066

M
Mr.doob 已提交
1067 1068 1069 1070 1071 1072
	// Rendering

	this.render = function ( scene, camera, renderTarget, forceClear ) {

		if ( camera instanceof THREE.Camera === false ) {

1073
			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
M
Mr.doob 已提交
1074 1075 1076 1077
			return;

		}

M
Mr.doob 已提交
1078
		var fog = scene.fog;
M
Mr.doob 已提交
1079 1080 1081

		// reset caching for this frame

1082
		_currentGeometryProgram = '';
1083
		_currentMaterialId = - 1;
1084
		_currentCamera = null;
M
Mr.doob 已提交
1085 1086 1087 1088
		_lightsNeedUpdate = true;

		// update scene graph

1089
		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
M
Mr.doob 已提交
1090 1091 1092

		// update camera matrices and frustum

1093
		if ( camera.parent === null ) camera.updateMatrixWorld();
M
Mr.doob 已提交
1094 1095 1096 1097 1098 1099

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
		_frustum.setFromMatrix( _projScreenMatrix );

M
Mr.doob 已提交
1100
		lights.length = 0;
1101

M
Mr.doob 已提交
1102 1103
		opaqueObjectsLastIndex = - 1;
		transparentObjectsLastIndex = - 1;
1104

M
Mr.doob 已提交
1105 1106 1107
		sprites.length = 0;
		lensFlares.length = 0;

1108
		projectObject( scene, camera );
M
Mr.doob 已提交
1109

1110 1111 1112
		opaqueObjects.length = opaqueObjectsLastIndex + 1;
		transparentObjects.length = transparentObjectsLastIndex + 1;

M
Mr.doob 已提交
1113
		if ( _this.sortObjects === true ) {
1114 1115 1116

			opaqueObjects.sort( painterSortStable );
			transparentObjects.sort( reversePainterSortStable );
M
Mr.doob 已提交
1117

1118 1119
		}

M
Mr.doob 已提交
1120
		//
M
Mr.doob 已提交
1121

M
Mr.doob 已提交
1122
		shadowMap.render( scene, camera );
M
Mr.doob 已提交
1123 1124 1125

		//

1126 1127 1128 1129
		_infoRender.calls = 0;
		_infoRender.vertices = 0;
		_infoRender.faces = 0;
		_infoRender.points = 0;
M
Mr.doob 已提交
1130 1131 1132 1133 1134 1135 1136 1137 1138

		this.setRenderTarget( renderTarget );

		if ( this.autoClear || forceClear ) {

			this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );

		}

1139
		//
M
Mr.doob 已提交
1140 1141 1142

		if ( scene.overrideMaterial ) {

1143
			var overrideMaterial = scene.overrideMaterial;
M
Mr.doob 已提交
1144

1145 1146
			renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
			renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
1147

M
Mr.doob 已提交
1148 1149 1150 1151
		} else {

			// opaque pass (front-to-back order)

M
Mr.doob 已提交
1152
			state.setBlending( THREE.NoBlending );
1153
			renderObjects( opaqueObjects, camera, lights, fog );
M
Mr.doob 已提交
1154 1155 1156

			// transparent pass (back-to-front order)

1157
			renderObjects( transparentObjects, camera, lights, fog );
M
Mr.doob 已提交
1158 1159 1160 1161 1162

		}

		// custom render plugins (post pass)

M
Mr.doob 已提交
1163 1164
		spritePlugin.render( scene, camera );
		lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
M
Mr.doob 已提交
1165 1166 1167

		// Generate mipmap if we're using any kind of mipmap filtering

M
Mr.doob 已提交
1168 1169 1170 1171 1172
		if ( renderTarget ) {

			var texture = renderTarget.texture;
			var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
			if ( texture.generateMipmaps && isTargetPowerOfTwo && texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
M
Mr.doob 已提交
1173

M
Mr.doob 已提交
1174 1175 1176
				 updateRenderTargetMipmap( renderTarget );

			}
M
Mr.doob 已提交
1177 1178 1179 1180 1181

		}

		// Ensure depth buffer writing is enabled so it can be cleared on next render

M
Mr.doob 已提交
1182 1183
		state.setDepthTest( true );
		state.setDepthWrite( true );
1184
		state.setColorWrite( true );
M
Mr.doob 已提交
1185 1186 1187 1188

		// _gl.finish();

	};
M
Mr.doob 已提交
1189

M
Mr.doob 已提交
1190 1191
	function pushRenderItem( object, geometry, material, z, group ) {

1192
		var array, index;
M
Mr.doob 已提交
1193

1194
		// allocate the next position in the appropriate array
M
Mr.doob 已提交
1195 1196 1197

		if ( material.transparent ) {

1198 1199
			array = transparentObjects;
			index = ++ transparentObjectsLastIndex;
M
Mr.doob 已提交
1200 1201 1202

		} else {

1203 1204 1205 1206 1207
			array = opaqueObjects;
			index = ++ opaqueObjectsLastIndex;

		}

1208 1209
		// recycle existing render item or grow the array

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
		var renderItem = array[ index ];

		if ( renderItem !== undefined ) {

			renderItem.id = object.id;
			renderItem.object = object;
			renderItem.geometry = geometry;
			renderItem.material = material;
			renderItem.z = _vector3.z;
			renderItem.group = group;
M
Mr.doob 已提交
1220 1221 1222

		} else {

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
			renderItem = {
				id: object.id,
				object: object,
				geometry: geometry,
				material: material,
				z: _vector3.z,
				group: group
			};

			// assert( index === array.length );
			array.push( renderItem );
M
Mr.doob 已提交
1234 1235 1236 1237 1238

		}

	}

1239
	function projectObject( object, camera ) {
M
Mr.doob 已提交
1240

M
Mr.doob 已提交
1241
		if ( object.visible === false ) return;
M
Mr.doob 已提交
1242

1243
		if ( object.layers.test( camera.layers ) ) {
M
Mr.doob 已提交
1244

1245
			if ( object instanceof THREE.Light ) {
M
Mr.doob 已提交
1246

1247
				lights.push( object );
M
Mr.doob 已提交
1248

1249
			} else if ( object instanceof THREE.Sprite ) {
M
Mr.doob 已提交
1250

1251 1252 1253 1254 1255
				if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {

					sprites.push( object );

				}
M
Mr.doob 已提交
1256

1257
			} else if ( object instanceof THREE.LensFlare ) {
M
Mr.doob 已提交
1258

1259
				lensFlares.push( object );
M
Mr.doob 已提交
1260

1261
			} else if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1262

1263
				if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1264

1265 1266
					_vector3.setFromMatrixPosition( object.matrixWorld );
					_vector3.applyProjection( _projScreenMatrix );
M
Mr.doob 已提交
1267

1268
				}
1269

1270
				pushRenderItem( object, null, object.material, _vector3.z, null );
M
Mr.doob 已提交
1271

1272
			} else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
M
Mr.doob 已提交
1273

1274
				if ( object instanceof THREE.SkinnedMesh ) {
M
Mr.doob 已提交
1275

1276
					object.skeleton.update();
1277

1278
				}
1279

1280
				if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
1281

1282
					var material = object.material;
1283

1284
					if ( material.visible === true ) {
M
Mr.doob 已提交
1285

1286
						if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1287

1288 1289 1290 1291
							_vector3.setFromMatrixPosition( object.matrixWorld );
							_vector3.applyProjection( _projScreenMatrix );

						}
M
Mr.doob 已提交
1292

1293
						var geometry = objects.update( object );
M
Mr.doob 已提交
1294

1295
						if ( material instanceof THREE.MeshFaceMaterial ) {
1296

1297 1298
							var groups = geometry.groups;
							var materials = material.materials;
1299

1300
							for ( var i = 0, l = groups.length; i < l; i ++ ) {
1301

1302 1303
								var group = groups[ i ];
								var groupMaterial = materials[ group.materialIndex ];
1304

1305
								if ( groupMaterial.visible === true ) {
1306

1307 1308 1309
									pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );

								}
M
Mr.doob 已提交
1310

M
Mr.doob 已提交
1311
							}
M
Mr.doob 已提交
1312

1313
						} else {
M
Mr.doob 已提交
1314

1315
							pushRenderItem( object, geometry, material, _vector3.z, null );
1316

1317
						}
O
OpenShift guest 已提交
1318

1319
					}
M
Mr.doob 已提交
1320

1321
				}
M
Mr.doob 已提交
1322

1323
			}
M
Mr.doob 已提交
1324

M
Mr.doob 已提交
1325
		}
M
Mr.doob 已提交
1326

M
Mr.doob 已提交
1327
		var children = object.children;
M
Mr.doob 已提交
1328

M
Mr.doob 已提交
1329 1330
		for ( var i = 0, l = children.length; i < l; i ++ ) {

1331
			projectObject( children[ i ], camera );
M
Mr.doob 已提交
1332

1333
		}
1334

1335
	}
M
Mr.doob 已提交
1336

1337
	function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
M
Mr.doob 已提交
1338

M
Mr.doob 已提交
1339
		for ( var i = 0, l = renderList.length; i < l; i ++ ) {
M
Mr.doob 已提交
1340

1341
			var renderItem = renderList[ i ];
M
Mr.doob 已提交
1342

1343
			var object = renderItem.object;
M
Mr.doob 已提交
1344 1345 1346
			var geometry = renderItem.geometry;
			var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
			var group = renderItem.group;
M
Mr.doob 已提交
1347

1348 1349
			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
M
Mr.doob 已提交
1350

M
Mr.doob 已提交
1351
			if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1352

M
Mr.doob 已提交
1353
				setMaterial( material );
M
Mr.doob 已提交
1354

M
Mr.doob 已提交
1355
				var program = setProgram( camera, lights, fog, material, object );
M
Mr.doob 已提交
1356

M
Mr.doob 已提交
1357
				_currentGeometryProgram = '';
M
Mr.doob 已提交
1358

M
Mr.doob 已提交
1359
				object.render( function ( object ) {
M
Mr.doob 已提交
1360

M
Mr.doob 已提交
1361
					_this.renderBufferImmediate( object, program, material );
M
Mr.doob 已提交
1362

M
Mr.doob 已提交
1363
				} );
1364

M
Mr.doob 已提交
1365
			} else {
M
Mr.doob 已提交
1366

M
Mr.doob 已提交
1367
				_this.renderBufferDirect( camera, lights, fog, geometry, material, object, group );
M
Mr.doob 已提交
1368

M
Mr.doob 已提交
1369
			}
M
Mr.doob 已提交
1370

1371
		}
M
Mr.doob 已提交
1372

1373
	}
G
gero3 已提交
1374

1375
	function initMaterial( material, lights, fog, object ) {
M
Mr.doob 已提交
1376

1377
		var materialProperties = properties.get( material );
G
gero3 已提交
1378 1379

		var parameters = programCache.getParameters( material, lights, fog, object );
G
gero3 已提交
1380
		var code = programCache.getProgramCode( material, parameters );
G
gero3 已提交
1381

1382
		var program = materialProperties.program;
T
tschw 已提交
1383
		var programChange = true;
1384

1385
		if ( program === undefined ) {
B
Ben Adams 已提交
1386

M
Mr.doob 已提交
1387 1388
			// new material
			material.addEventListener( 'dispose', onMaterialDispose );
B
Ben Adams 已提交
1389

1390
		} else if ( program.code !== code ) {
B
Ben Adams 已提交
1391

M
Mr.doob 已提交
1392
			// changed glsl or parameters
1393
			releaseMaterialProgramReference( material );
B
Ben Adams 已提交
1394

G
gero3 已提交
1395
		} else if ( parameters.shaderID !== undefined ) {
B
Ben Adams 已提交
1396

T
tschw 已提交
1397
			// same glsl and uniform list
T
tschw 已提交
1398 1399
			return;

T
tschw 已提交
1400
		} else {
B
Ben Adams 已提交
1401

T
tschw 已提交
1402 1403
			// only rebuild uniform list
			programChange = false;
B
Ben Adams 已提交
1404 1405 1406

		}

1407
		if ( programChange ) {
B
Ben Adams 已提交
1408

1409
			if ( parameters.shaderID ) {
B
Ben Adams 已提交
1410

1411
				var shader = THREE.ShaderLib[ parameters.shaderID ];
B
Ben Adams 已提交
1412

1413 1414 1415 1416 1417 1418
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};
B
Ben Adams 已提交
1419

1420
			} else {
B
Ben Adams 已提交
1421

1422 1423 1424 1425 1426 1427
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};
G
gero3 已提交
1428

1429
			}
G
gero3 已提交
1430

1431
			material.__webglShader = materialProperties.__webglShader;
G
gero3 已提交
1432

1433
			program = programCache.acquireProgram( material, parameters, code );
B
Ben Adams 已提交
1434

1435 1436
			materialProperties.program = program;
			material.program = program;
1437 1438 1439

		}

1440
		var attributes = program.getAttributes();
M
Mr.doob 已提交
1441 1442 1443 1444 1445

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

1446
			for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
M
Mr.doob 已提交
1447

M
Mr.doob 已提交
1448
				if ( attributes[ 'morphTarget' + i ] >= 0 ) {
M
Mr.doob 已提交
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

1462
			for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
M
Mr.doob 已提交
1463

M
Mr.doob 已提交
1464
				if ( attributes[ 'morphNormal' + i ] >= 0 ) {
M
Mr.doob 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473

					material.numSupportedMorphNormals ++;

				}

			}

		}

1474
		materialProperties.uniformsList = [];
M
Mr.doob 已提交
1475

1476 1477
		var uniforms = materialProperties.__webglShader.uniforms,
			uniformLocations = materialProperties.program.getUniforms();
M
Mr.doob 已提交
1478

1479
		for ( var u in uniforms ) {
M
Mr.doob 已提交
1480

1481
			var location = uniformLocations[ u ];
1482 1483

			if ( location ) {
G
gero3 已提交
1484

1485
				materialProperties.uniformsList.push( [ materialProperties.__webglShader.uniforms[ u ], location ] );
G
gero3 已提交
1486

1487
			}
M
Mr.doob 已提交
1488 1489 1490

		}

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
		if ( material instanceof THREE.MeshPhongMaterial ||
				material instanceof THREE.MeshLambertMaterial ||
				material instanceof THREE.MeshPhysicalMaterial ||
				material.lights ) {

			// wire up the material to this renderer's lighting state

			uniforms.ambientLightColor.value = _lights.ambient;
			uniforms.directionalLights.value = _lights.directional;
			uniforms.pointLights.value = _lights.point;
			uniforms.spotLights.value = _lights.spot;
			uniforms.hemisphereLights.value = _lights.hemi;

		}

M
Mr.doob 已提交
1506
	}
M
Mr.doob 已提交
1507

1508 1509
	function setMaterial( material ) {

M
Mr.doob 已提交
1510 1511
		setMaterialFaces( material );

1512 1513
		if ( material.transparent === true ) {

M
Mr.doob 已提交
1514
			state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
1515

1516 1517 1518 1519
		} else {

			state.setBlending( THREE.NoBlending );

1520 1521
		}

B
Ben Adams 已提交
1522
		state.setDepthFunc( material.depthFunc );
M
Mr.doob 已提交
1523 1524
		state.setDepthTest( material.depthTest );
		state.setDepthWrite( material.depthWrite );
1525
		state.setColorWrite( material.colorWrite );
M
Mr.doob 已提交
1526
		state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
1527 1528 1529

	}

M
Mr.doob 已提交
1530 1531
	function setMaterialFaces( material ) {

1532
		material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
1533 1534 1535 1536
		state.setFlipSided( material.side === THREE.BackSide );

	}

M
Mr.doob 已提交
1537 1538 1539 1540
	function setProgram( camera, lights, fog, material, object ) {

		_usedTextureUnits = 0;

1541
		var materialProperties = properties.get( material );
1542

1543
		if ( material.needsUpdate || ! materialProperties.program ) {
M
Mr.doob 已提交
1544

1545
			initMaterial( material, lights, fog, object );
M
Mr.doob 已提交
1546 1547 1548 1549
			material.needsUpdate = false;

		}

1550
		var refreshProgram = false;
M
Mr.doob 已提交
1551
		var refreshMaterial = false;
1552
		var refreshLights = false;
M
Mr.doob 已提交
1553

1554
		var program = materialProperties.program,
1555
			p_uniforms = program.getUniforms(),
1556
			m_uniforms = materialProperties.__webglShader.uniforms;
M
Mr.doob 已提交
1557

1558
		if ( program.id !== _currentProgram ) {
M
Mr.doob 已提交
1559

1560 1561
			_gl.useProgram( program.program );
			_currentProgram = program.id;
M
Mr.doob 已提交
1562

1563
			refreshProgram = true;
M
Mr.doob 已提交
1564
			refreshMaterial = true;
1565
			refreshLights = true;
M
Mr.doob 已提交
1566 1567 1568 1569 1570 1571

		}

		if ( material.id !== _currentMaterialId ) {

			_currentMaterialId = material.id;
1572

M
Mr.doob 已提交
1573 1574 1575 1576
			refreshMaterial = true;

		}

1577
		if ( refreshProgram || camera !== _currentCamera ) {
M
Mr.doob 已提交
1578 1579 1580

			_gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );

G
gero3 已提交
1581
			if ( capabilities.logarithmicDepthBuffer ) {
1582

1583
				_gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
1584 1585 1586 1587

			}


1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
			if ( camera !== _currentCamera ) {

				_currentCamera = camera;

				// lighting uniforms depend on the camera so enforce an update
				// now, in case this material supports lights - or later, when
				// the next material that does gets activated:

				refreshMaterial = true;		// set to true on material change
				_lightsNeedUpdate = true;	// remains set until update done

			}
M
Mr.doob 已提交
1600

1601 1602 1603 1604 1605
			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

			if ( material instanceof THREE.ShaderMaterial ||
				 material instanceof THREE.MeshPhongMaterial ||
1606
				 material instanceof THREE.MeshPhysicalMaterial ||
1607 1608
				 material.envMap ) {

1609
				if ( p_uniforms.cameraPosition !== undefined ) {
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

					_vector3.setFromMatrixPosition( camera.matrixWorld );
					_gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );

				}

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1620
				 material instanceof THREE.MeshBasicMaterial ||
1621
				 material instanceof THREE.MeshPhysicalMaterial ||
1622 1623 1624
				 material instanceof THREE.ShaderMaterial ||
				 material.skinning ) {

1625
				if ( p_uniforms.viewMatrix !== undefined ) {
1626 1627

					_gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
M
Mr.doob 已提交
1628

1629 1630 1631 1632
				}

			}

M
Mr.doob 已提交
1633 1634 1635 1636 1637 1638 1639 1640
		}

		// skinning uniforms must be set even if material didn't change
		// auto-setting of texture unit for bone texture must go before other textures
		// not sure why, but otherwise weird things happen

		if ( material.skinning ) {

1641
			if ( object.bindMatrix && p_uniforms.bindMatrix !== undefined ) {
1642 1643 1644 1645 1646

				_gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );

			}

1647
			if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== undefined ) {
1648 1649 1650 1651 1652

				_gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );

			}

1653
			if ( capabilities.floatVertexTextures && object.skeleton && object.skeleton.useVertexTexture ) {
M
Mr.doob 已提交
1654

1655
				if ( p_uniforms.boneTexture !== undefined ) {
M
Mr.doob 已提交
1656 1657 1658 1659

					var textureUnit = getTextureUnit();

					_gl.uniform1i( p_uniforms.boneTexture, textureUnit );
1660
					_this.setTexture( object.skeleton.boneTexture, textureUnit );
M
Mr.doob 已提交
1661 1662 1663

				}

1664
				if ( p_uniforms.boneTextureWidth !== undefined ) {
1665

1666
					_gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
1667 1668 1669

				}

1670
				if ( p_uniforms.boneTextureHeight !== undefined ) {
1671

1672
					_gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
1673 1674 1675

				}

1676
			} else if ( object.skeleton && object.skeleton.boneMatrices ) {
M
Mr.doob 已提交
1677

1678
				if ( p_uniforms.boneGlobalMatrices !== undefined ) {
M
Mr.doob 已提交
1679

1680
					_gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
M
Mr.doob 已提交
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

				}

			}

		}

		if ( refreshMaterial ) {

			// refresh uniforms common to several materials

			if ( fog && material.fog ) {

				refreshUniformsFog( m_uniforms, fog );

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1700
				 material instanceof THREE.MeshPhysicalMaterial ||
M
Mr.doob 已提交
1701 1702
				 material.lights ) {

1703
				// the current material requires lighting info
M
Mr.doob 已提交
1704

1705 1706 1707
				// if we haven't done so since the start of the frame, after a
				// reset or camera change, update the lighting uniforms values
				// of all materials (by reference)
G
gero3 已提交
1708

1709
				if ( _lightsNeedUpdate ) {
M
Mr.doob 已提交
1710

1711
					_lightsNeedUpdate = false;
G
gero3 已提交
1712

1713 1714
					setupLights( lights, camera );
					refreshLights = true;
G
gero3 已提交
1715

1716
				}
G
gero3 已提交
1717

1718 1719
				// use the current material's .needsUpdate flags to set
				// the GL state when required
G
gero3 已提交
1720

1721
				markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
M
Mr.doob 已提交
1722 1723 1724 1725 1726

			}

			if ( material instanceof THREE.MeshBasicMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
W
WestLangley 已提交
1727
				 material instanceof THREE.MeshPhongMaterial ||
1728
				 material instanceof THREE.MeshPhysicalMaterial ) {
M
Mr.doob 已提交
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

				refreshUniformsCommon( m_uniforms, material );

			}

			// refresh single material specific uniforms

			if ( material instanceof THREE.LineBasicMaterial ) {

				refreshUniformsLine( m_uniforms, material );

			} else if ( material instanceof THREE.LineDashedMaterial ) {

				refreshUniformsLine( m_uniforms, material );
				refreshUniformsDash( m_uniforms, material );

1745
			} else if ( material instanceof THREE.PointsMaterial ) {
M
Mr.doob 已提交
1746

M
Mr.doob 已提交
1747
				refreshUniformsPoints( m_uniforms, material );
M
Mr.doob 已提交
1748 1749 1750 1751 1752

			} else if ( material instanceof THREE.MeshPhongMaterial ) {

				refreshUniformsPhong( m_uniforms, material );

1753
			} else if ( material instanceof THREE.MeshPhysicalMaterial ) {
W
WestLangley 已提交
1754 1755 1756

				refreshUniformsStandard( m_uniforms, material );

M
Mr.doob 已提交
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
			} else if ( material instanceof THREE.MeshDepthMaterial ) {

				m_uniforms.mNear.value = camera.near;
				m_uniforms.mFar.value = camera.far;
				m_uniforms.opacity.value = material.opacity;

			} else if ( material instanceof THREE.MeshNormalMaterial ) {

				m_uniforms.opacity.value = material.opacity;

			}

M
Mr.doob 已提交
1769
			if ( shadowMap.enabled ) {
M
Mr.doob 已提交
1770

1771 1772 1773 1774 1775
				if ( object.receiveShadow && ! material._shadowPass ) {

					refreshUniformsShadow( m_uniforms, lights, camera );

				}
M
Mr.doob 已提交
1776 1777 1778 1779 1780

			}

			// load common uniforms

1781
			loadUniformsGeneric( materialProperties.uniformsList );
M
Mr.doob 已提交
1782 1783 1784 1785 1786

		}

		loadUniformsMatrices( p_uniforms, object );

1787
		if ( p_uniforms.modelMatrix !== undefined ) {
M
Mr.doob 已提交
1788 1789

			_gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
M
Mr.doob 已提交
1790

M
Mr.doob 已提交
1791 1792 1793 1794
		}

		return program;

M
Mr.doob 已提交
1795
	}
M
Mr.doob 已提交
1796 1797 1798 1799 1800 1801 1802

	// Uniforms (refresh uniforms objects)

	function refreshUniformsCommon ( uniforms, material ) {

		uniforms.opacity.value = material.opacity;

1803
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
1804

1805
		if ( material.emissive ) {
M
Mr.doob 已提交
1806

1807
			uniforms.emissive.value = material.emissive;
M
Mr.doob 已提交
1808 1809 1810

		}

1811 1812 1813
		uniforms.map.value = material.map;
		uniforms.specularMap.value = material.specularMap;
		uniforms.alphaMap.value = material.alphaMap;
M
Mr.doob 已提交
1814

1815
		if ( material.aoMap ) {
1816

1817 1818
			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;
1819 1820 1821

		}

M
Mr.doob 已提交
1822
		// uv repeat and offset setting priorities
M
Mr.doob 已提交
1823 1824 1825 1826 1827
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
1828
		// 6. emissive map
M
Mr.doob 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839

		var uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

1840 1841 1842 1843
		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

M
Mr.doob 已提交
1844 1845 1846 1847 1848 1849 1850 1851
		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

1852 1853 1854 1855
		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

1856 1857 1858 1859
		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

M
Mr.doob 已提交
1860 1861 1862 1863
		}

		if ( uvScaleMap !== undefined ) {

M
Mr.doob 已提交
1864
			if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) uvScaleMap = uvScaleMap.texture;
M
Mr.doob 已提交
1865 1866 1867 1868 1869 1870 1871 1872
			var offset = uvScaleMap.offset;
			var repeat = uvScaleMap.repeat;

			uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

		}

		uniforms.envMap.value = material.envMap;
1873
		uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
M
Mr.doob 已提交
1874

1875
		uniforms.reflectivity.value = material.reflectivity;
M
Mr.doob 已提交
1876 1877
		uniforms.refractionRatio.value = material.refractionRatio;

M
Mr.doob 已提交
1878
	}
M
Mr.doob 已提交
1879 1880 1881 1882 1883 1884

	function refreshUniformsLine ( uniforms, material ) {

		uniforms.diffuse.value = material.color;
		uniforms.opacity.value = material.opacity;

M
Mr.doob 已提交
1885
	}
M
Mr.doob 已提交
1886 1887 1888 1889 1890 1891 1892

	function refreshUniformsDash ( uniforms, material ) {

		uniforms.dashSize.value = material.dashSize;
		uniforms.totalSize.value = material.dashSize + material.gapSize;
		uniforms.scale.value = material.scale;

M
Mr.doob 已提交
1893
	}
M
Mr.doob 已提交
1894

M
Mr.doob 已提交
1895
	function refreshUniformsPoints ( uniforms, material ) {
M
Mr.doob 已提交
1896 1897 1898

		uniforms.psColor.value = material.color;
		uniforms.opacity.value = material.opacity;
1899
		uniforms.size.value = material.size * pixelRatio;
M
Mr.doob 已提交
1900 1901 1902 1903
		uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.

		uniforms.map.value = material.map;

1904 1905 1906 1907 1908 1909 1910 1911 1912
		if ( material.map !== null ) {

			var offset = material.map.offset;
			var repeat = material.map.repeat;

			uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

		}

M
Mr.doob 已提交
1913
	}
M
Mr.doob 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929

	function refreshUniformsFog ( uniforms, fog ) {

		uniforms.fogColor.value = fog.color;

		if ( fog instanceof THREE.Fog ) {

			uniforms.fogNear.value = fog.near;
			uniforms.fogFar.value = fog.far;

		} else if ( fog instanceof THREE.FogExp2 ) {

			uniforms.fogDensity.value = fog.density;

		}

M
Mr.doob 已提交
1930
	}
M
Mr.doob 已提交
1931 1932 1933

	function refreshUniformsPhong ( uniforms, material ) {

1934
		uniforms.specular.value = material.specular;
M
Mr.doob 已提交
1935
		uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
M
Mr.doob 已提交
1936

1937 1938 1939 1940
		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;
M
Mr.doob 已提交
1941

1942
		}
1943

1944
		if ( material.emissiveMap ) {
1945

1946
			uniforms.emissiveMap.value = material.emissiveMap;
1947

1948
		}
M
Mr.doob 已提交
1949

1950 1951 1952 1953
		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
M
Mr.doob 已提交
1954

1955
		}
M
Mr.doob 已提交
1956

1957 1958 1959 1960 1961 1962
		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );

		}
M
Mr.doob 已提交
1963

1964 1965 1966 1967 1968
		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;
1969

1970
		}
1971 1972 1973

	}

W
WestLangley 已提交
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
	function refreshUniformsStandard ( uniforms, material ) {

		uniforms.roughness.value = material.roughness;
		//uniforms.reflectivity.value = material.reflectivity; // part of uniforms common
		uniforms.metalness.value = material.metalness;

		if ( material.roughnessMap ) {

			uniforms.roughnessMap.value = material.roughnessMap;

		}

		if ( material.reflectivityMap ) {

			uniforms.reflectivityMap.value = material.reflectivityMap;

		}

		if ( material.metalnessMap ) {

			uniforms.metalnessMap.value = material.metalnessMap;

		}

		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

		if ( material.envMap ) {

			//uniforms.envMap.value = material.envMap; // part of uniforms common
			uniforms.envMapIntensity.value = material.envMapIntensity;

		}

	}

2042 2043
	// If uniforms are marked as clean, they don't need to be loaded to the GPU.

M
Mr.doob 已提交
2044
	function markUniformsLightsNeedsUpdate ( uniforms, value ) {
2045

M
Mr.doob 已提交
2046
		uniforms.ambientLightColor.needsUpdate = value;
2047

B
Ben Houston 已提交
2048 2049 2050 2051
		uniforms.directionalLights.needsUpdate = value;
		uniforms.pointLights.needsUpdate = value;
		uniforms.spotLights.needsUpdate = value;
		uniforms.hemisphereLights.needsUpdate = value;
2052

M
Mr.doob 已提交
2053
	}
2054

M
Mr.doob 已提交
2055
	function refreshUniformsShadow ( uniforms, lights, camera ) {
M
Mr.doob 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064

		if ( uniforms.shadowMatrix ) {

			var j = 0;

			for ( var i = 0, il = lights.length; i < il; i ++ ) {

				var light = lights[ i ];

M
Mr.doob 已提交
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
				if ( light.castShadow === true ) {

					if ( light instanceof THREE.PointLight || light instanceof THREE.SpotLight || light instanceof THREE.DirectionalLight ) {

						var shadow = light.shadow;

						if ( light instanceof THREE.PointLight ) {

							// for point lights we set the shadow matrix to be a translation-only matrix
							// equal to inverse of the light's position
							_vector3.setFromMatrixPosition( light.matrixWorld ).negate();
							shadow.matrix.identity().setPosition( _vector3 );

							// for point lights we set the sign of the shadowDarkness uniform to be negative
							uniforms.shadowDarkness.value[ j ] = - shadow.darkness;

						} else {
M
Mr.doob 已提交
2082

M
Mr.doob 已提交
2083
							uniforms.shadowDarkness.value[ j ] = shadow.darkness;
M
Mr.doob 已提交
2084

M
Mr.doob 已提交
2085
						}
M
Mr.doob 已提交
2086

M
Mr.doob 已提交
2087 2088 2089 2090
						uniforms.shadowMatrix.value[ j ] = shadow.matrix;
						uniforms.shadowMap.value[ j ] = shadow.map;
						uniforms.shadowMapSize.value[ j ] = shadow.mapSize;
						uniforms.shadowBias.value[ j ] = shadow.bias;
M
Mr.doob 已提交
2091

M
Mr.doob 已提交
2092
						j ++;
M
Mr.doob 已提交
2093

M
Mr.doob 已提交
2094
					}
M
Mr.doob 已提交
2095 2096 2097 2098 2099 2100 2101

				}

			}

		}

M
Mr.doob 已提交
2102
	}
M
Mr.doob 已提交
2103 2104 2105 2106 2107

	// Uniforms (load to GPU)

	function loadUniformsMatrices ( uniforms, object ) {

2108
		_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );
M
Mr.doob 已提交
2109 2110 2111

		if ( uniforms.normalMatrix ) {

2112
			_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );
M
Mr.doob 已提交
2113 2114 2115

		}

M
Mr.doob 已提交
2116
	}
M
Mr.doob 已提交
2117 2118 2119 2120 2121

	function getTextureUnit() {

		var textureUnit = _usedTextureUnits;

G
gero3 已提交
2122
		if ( textureUnit >= capabilities.maxTextures ) {
M
Mr.doob 已提交
2123

G
gero3 已提交
2124
			console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
M
Mr.doob 已提交
2125 2126 2127 2128 2129 2130 2131

		}

		_usedTextureUnits += 1;

		return textureUnit;

M
Mr.doob 已提交
2132
	}
M
Mr.doob 已提交
2133

2134
	function loadUniformsGeneric ( uniforms ) {
M
Mr.doob 已提交
2135

M
Mr.doob 已提交
2136
		var texture, textureUnit;
M
Mr.doob 已提交
2137

M
Mr.doob 已提交
2138 2139 2140
		for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {

			var uniform = uniforms[ j ][ 0 ];
M
Mr.doob 已提交
2141

2142 2143
			// needsUpdate property is not added to all uniforms.
			if ( uniform.needsUpdate === false ) continue;
2144

M
Mr.doob 已提交
2145 2146
			var type = uniform.type;
			var value = uniform.value;
2147
			var location = uniforms[ j ][ 1 ];
M
Mr.doob 已提交
2148

2149
			switch ( type ) {
M
Mr.doob 已提交
2150

2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
				case '1i':
					_gl.uniform1i( location, value );
					break;

				case '1f':
					_gl.uniform1f( location, value );
					break;

				case '2f':
					_gl.uniform2f( location, value[ 0 ], value[ 1 ] );
					break;

				case '3f':
					_gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
					break;

				case '4f':
					_gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
					break;

				case '1iv':
					_gl.uniform1iv( location, value );
					break;

				case '3iv':
					_gl.uniform3iv( location, value );
					break;

				case '1fv':
					_gl.uniform1fv( location, value );
					break;

				case '2fv':
					_gl.uniform2fv( location, value );
					break;

				case '3fv':
					_gl.uniform3fv( location, value );
					break;

				case '4fv':
					_gl.uniform4fv( location, value );
					break;

				case 'Matrix3fv':
					_gl.uniformMatrix3fv( location, false, value );
					break;

				case 'Matrix4fv':
					_gl.uniformMatrix4fv( location, false, value );
					break;

				//

M
Mr.doob 已提交
2205
				case 'i':
M
Mr.doob 已提交
2206

2207 2208
					// single integer
					_gl.uniform1i( location, value );
M
Mr.doob 已提交
2209

2210
					break;
M
Mr.doob 已提交
2211

2212
				case 'f':
M
Mr.doob 已提交
2213

2214 2215
					// single float
					_gl.uniform1f( location, value );
M
Mr.doob 已提交
2216

2217
					break;
M
Mr.doob 已提交
2218

2219
				case 'v2':
M
Mr.doob 已提交
2220

2221 2222
					// single THREE.Vector2
					_gl.uniform2f( location, value.x, value.y );
M
Mr.doob 已提交
2223

2224
					break;
M
Mr.doob 已提交
2225

2226
				case 'v3':
M
Mr.doob 已提交
2227

2228 2229
					// single THREE.Vector3
					_gl.uniform3f( location, value.x, value.y, value.z );
M
Mr.doob 已提交
2230

2231
					break;
M
Mr.doob 已提交
2232

M
Mr.doob 已提交
2233
				case 'v4':
M
Mr.doob 已提交
2234

2235 2236
					// single THREE.Vector4
					_gl.uniform4f( location, value.x, value.y, value.z, value.w );
M
Mr.doob 已提交
2237

2238
					break;
M
Mr.doob 已提交
2239

2240
				case 'c':
M
Mr.doob 已提交
2241

2242 2243
					// single THREE.Color
					_gl.uniform3f( location, value.r, value.g, value.b );
M
Mr.doob 已提交
2244

2245
					break;
M
Mr.doob 已提交
2246

2247 2248 2249
				case 's':

					// TODO: Optimize this.
B
Ben Houston 已提交
2250
					for( var propertyName in uniform.properties ) {
M
Mr.doob 已提交
2251

B
Ben Houston 已提交
2252 2253 2254
						var property = uniform.properties[ propertyName ];
						var locationProperty =  location[ propertyName ];
						var valueProperty = value[ propertyName ];
M
Mr.doob 已提交
2255

2256 2257
						switch( property.type ) {
							case 'f':
B
Ben Houston 已提交
2258
								_gl.uniform1f( locationProperty, valueProperty );
2259 2260
								break;
							case 'v2':
B
Ben Houston 已提交
2261
								_gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
2262 2263
								break;
							case 'v3':
B
Ben Houston 已提交
2264
								_gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
2265 2266
								break;
							case 'v4':
B
Ben Houston 已提交
2267
								_gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
2268 2269
								break;
							case 'c':
B
Ben Houston 已提交
2270
								_gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
2271 2272
								break;
						};
2273 2274 2275 2276 2277

					}

					break;

2278
				case 'sa':
2279

2280
					// TODO: Optimize this.
2281 2282
					for( var i = 0; i < value.length; i ++ ) {

B
Ben Houston 已提交
2283
						for( var propertyName in uniform.properties ) {
M
Mr.doob 已提交
2284

B
Ben Houston 已提交
2285 2286 2287
							var property = uniform.properties[ propertyName ];
							var locationProperty =  location[ i ][ propertyName ];
							var valueProperty = value[i][ propertyName ];
M
Mr.doob 已提交
2288

2289 2290
							switch( property.type ) {
								case 'f':
B
Ben Houston 已提交
2291
									_gl.uniform1f( locationProperty, valueProperty );
2292 2293
									break;
								case 'v2':
B
Ben Houston 已提交
2294
									_gl.uniform2f( locationProperty, valueProperty.x, valueProperty.y );
2295 2296
									break;
								case 'v3':
B
Ben Houston 已提交
2297
									_gl.uniform3f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z );
2298 2299
									break;
								case 'v4':
B
Ben Houston 已提交
2300
									_gl.uniform4f( locationProperty, valueProperty.x, valueProperty.y, valueProperty.z, valueProperty.w );
2301 2302
									break;
								case 'c':
B
Ben Houston 已提交
2303
									_gl.uniform3f( locationProperty, valueProperty.r, valueProperty.g, valueProperty.b );
2304 2305
									break;
							};
2306

2307
						}
2308 2309

					}
M
Mr.doob 已提交
2310

2311 2312
					break;

2313
				case 'iv1':
M
Mr.doob 已提交
2314

2315 2316
					// flat array of integers (JS or typed array)
					_gl.uniform1iv( location, value );
M
Mr.doob 已提交
2317

2318
					break;
M
Mr.doob 已提交
2319

2320
				case 'iv':
M
Mr.doob 已提交
2321

2322 2323
					// flat array of integers with 3 x N size (JS or typed array)
					_gl.uniform3iv( location, value );
M
Mr.doob 已提交
2324

2325
					break;
M
Mr.doob 已提交
2326

2327
				case 'fv1':
M
Mr.doob 已提交
2328

2329 2330
					// flat array of floats (JS or typed array)
					_gl.uniform1fv( location, value );
M
Mr.doob 已提交
2331

2332
					break;
M
Mr.doob 已提交
2333

2334
				case 'fv':
M
Mr.doob 已提交
2335

2336 2337
					// flat array of floats with 3 x N size (JS or typed array)
					_gl.uniform3fv( location, value );
M
Mr.doob 已提交
2338

2339
					break;
M
Mr.doob 已提交
2340

2341
				case 'v2v':
M
Mr.doob 已提交
2342

2343
					// array of THREE.Vector2
M
Mr.doob 已提交
2344

2345
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2346

2347
						uniform._array = new Float32Array( 2 * value.length );
M
Mr.doob 已提交
2348

2349
					}
M
Mr.doob 已提交
2350

M
Mr.doob 已提交
2351
					for ( var i = 0, i2 = 0, il = value.length; i < il; i ++, i2 += 2 ) {
M
Mr.doob 已提交
2352

M
Mr.doob 已提交
2353 2354
						uniform._array[ i2 + 0 ] = value[ i ].x;
						uniform._array[ i2 + 1 ] = value[ i ].y;
M
Mr.doob 已提交
2355

2356
					}
M
Mr.doob 已提交
2357

2358
					_gl.uniform2fv( location, uniform._array );
M
Mr.doob 已提交
2359

2360
					break;
M
Mr.doob 已提交
2361

2362
				case 'v3v':
M
Mr.doob 已提交
2363

2364
					// array of THREE.Vector3
M
Mr.doob 已提交
2365

2366
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2367

2368
						uniform._array = new Float32Array( 3 * value.length );
M
Mr.doob 已提交
2369

2370
					}
M
Mr.doob 已提交
2371

M
Mr.doob 已提交
2372
					for ( var i = 0, i3 = 0, il = value.length; i < il; i ++, i3 += 3 ) {
R
Ryan Tsao 已提交
2373

M
Mr.doob 已提交
2374 2375 2376
						uniform._array[ i3 + 0 ] = value[ i ].x;
						uniform._array[ i3 + 1 ] = value[ i ].y;
						uniform._array[ i3 + 2 ] = value[ i ].z;
R
Ryan Tsao 已提交
2377

2378
					}
R
Ryan Tsao 已提交
2379

2380
					_gl.uniform3fv( location, uniform._array );
R
Ryan Tsao 已提交
2381

2382
					break;
R
Ryan Tsao 已提交
2383

2384
				case 'v4v':
R
Ryan Tsao 已提交
2385

2386
					// array of THREE.Vector4
R
Ryan Tsao 已提交
2387

2388
					if ( uniform._array === undefined ) {
R
Ryan Tsao 已提交
2389

2390
						uniform._array = new Float32Array( 4 * value.length );
R
Ryan Tsao 已提交
2391

2392
					}
M
Mr.doob 已提交
2393

M
Mr.doob 已提交
2394
					for ( var i = 0, i4 = 0, il = value.length; i < il; i ++, i4 += 4 ) {
M
Mr.doob 已提交
2395

M
Mr.doob 已提交
2396 2397 2398 2399
						uniform._array[ i4 + 0 ] = value[ i ].x;
						uniform._array[ i4 + 1 ] = value[ i ].y;
						uniform._array[ i4 + 2 ] = value[ i ].z;
						uniform._array[ i4 + 3 ] = value[ i ].w;
M
Mr.doob 已提交
2400

2401
					}
M
Mr.doob 已提交
2402

2403
					_gl.uniform4fv( location, uniform._array );
M
Mr.doob 已提交
2404

2405
					break;
M
Mr.doob 已提交
2406

2407
				case 'm3':
M
Mr.doob 已提交
2408

2409 2410
					// single THREE.Matrix3
					_gl.uniformMatrix3fv( location, false, value.elements );
M
Mr.doob 已提交
2411

2412
					break;
M
Mr.doob 已提交
2413

2414
				case 'm3v':
M
Mr.doob 已提交
2415

2416
					// array of THREE.Matrix3
M
Mr.doob 已提交
2417

2418
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2419

2420
						uniform._array = new Float32Array( 9 * value.length );
M
Mr.doob 已提交
2421

2422
					}
M
Mr.doob 已提交
2423

2424
					for ( var i = 0, il = value.length; i < il; i ++ ) {
M
Mr.doob 已提交
2425

2426
						value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
M
Mr.doob 已提交
2427

2428
					}
M
Mr.doob 已提交
2429

2430
					_gl.uniformMatrix3fv( location, false, uniform._array );
M
Mr.doob 已提交
2431

2432
					break;
M
Mr.doob 已提交
2433

2434
				case 'm4':
M
Mr.doob 已提交
2435

2436 2437
					// single THREE.Matrix4
					_gl.uniformMatrix4fv( location, false, value.elements );
M
Mr.doob 已提交
2438

2439
					break;
M
Mr.doob 已提交
2440

2441
				case 'm4v':
M
Mr.doob 已提交
2442

2443
					// array of THREE.Matrix4
M
Mr.doob 已提交
2444

2445
					if ( uniform._array === undefined ) {
M
Mr.doob 已提交
2446

2447
						uniform._array = new Float32Array( 16 * value.length );
M
Mr.doob 已提交
2448

2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
					}

					for ( var i = 0, il = value.length; i < il; i ++ ) {

						value[ i ].flattenToArrayOffset( uniform._array, i * 16 );

					}

					_gl.uniformMatrix4fv( location, false, uniform._array );

					break;
M
Mr.doob 已提交
2460

2461
				case 't':
M
Mr.doob 已提交
2462

2463
					// single THREE.Texture (2d or cube)
M
Mr.doob 已提交
2464

2465 2466 2467 2468
					texture = value;
					textureUnit = getTextureUnit();

					_gl.uniform1i( location, textureUnit );
M
Mr.doob 已提交
2469

2470
					if ( ! texture ) continue;
M
Mr.doob 已提交
2471

2472
					if ( texture instanceof THREE.CubeTexture ||
G
gero3 已提交
2473 2474 2475
						 ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

						// CompressedTexture can have Array in image :/
M
Mr.doob 已提交
2476

2477
						setCubeTexture( texture, textureUnit );
M
Mr.doob 已提交
2478

2479 2480
					} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {

M
Mr.doob 已提交
2481 2482 2483 2484 2485
						setCubeTextureDynamic( texture.texture, textureUnit );

					} else if ( texture instanceof THREE.WebGLRenderTarget ) {

						_this.setTexture( texture.texture, textureUnit );
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

					} else {

						_this.setTexture( texture, textureUnit );

					}

					break;

				case 'tv':

M
Mr.doob 已提交
2497
					// array of THREE.Texture (2d or cube)
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

					if ( uniform._array === undefined ) {

						uniform._array = [];

					}

					for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {

						uniform._array[ i ] = getTextureUnit();

					}

					_gl.uniform1iv( location, uniform._array );

					for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {

						texture = uniform.value[ i ];
						textureUnit = uniform._array[ i ];

						if ( ! texture ) continue;

M
Mr.doob 已提交
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
						if ( texture instanceof THREE.CubeTexture ||
							 ( texture.image instanceof Array && texture.image.length === 6 ) ) {

							// CompressedTexture can have Array in image :/

							setCubeTexture( texture, textureUnit );

						} else if ( texture instanceof THREE.WebGLRenderTarget ) {

							_this.setTexture( texture.texture, textureUnit );

						} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {

							setCubeTextureDynamic( texture.texture, textureUnit );

						} else {

							_this.setTexture( texture, textureUnit );

						}
2540 2541 2542 2543 2544 2545

					}

					break;

				default:
2546

2547
					console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
2548

M
Mr.doob 已提交
2549 2550 2551 2552
			}

		}

M
Mr.doob 已提交
2553
	}
M
Mr.doob 已提交
2554

T
tschw 已提交
2555
	function setupLights ( lights, camera ) {
M
Mr.doob 已提交
2556

B
brason 已提交
2557
		var l, ll, light,
M
Mr.doob 已提交
2558
		r = 0, g = 0, b = 0,
B
Ben Houston 已提交
2559
		color,
B
brason 已提交
2560
		intensity,
M
Mr.doob 已提交
2561 2562 2563 2564
		distance,

		zlights = _lights,

2565
		viewMatrix = camera.matrixWorldInverse,
M
Mr.doob 已提交
2566

2567 2568 2569 2570
		writeIndexDirectional = 0,
		writeIndexPoint = 0,
		writeIndexSpot = 0,
		writeIndexHemi = 0;
M
Mr.doob 已提交
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583

		for ( l = 0, ll = lights.length; l < ll; l ++ ) {

			light = lights[ l ];

			color = light.color;
			intensity = light.intensity;
			distance = light.distance;

			if ( light instanceof THREE.AmbientLight ) {

				if ( ! light.visible ) continue;

2584 2585 2586
				r += color.r;
				g += color.g;
				b += color.b;
M
Mr.doob 已提交
2587 2588 2589

			} else if ( light instanceof THREE.DirectionalLight ) {

B
Ben Houston 已提交
2590 2591
				if( ! light.__webglUniforms ) {
					light.__webglUniforms = {
B
Ben Houston 已提交
2592 2593
						direction: new THREE.Vector3(),
						color: new THREE.Color()
B
Ben Houston 已提交
2594 2595
					}
				}
M
Mr.doob 已提交
2596

B
Ben Houston 已提交
2597
				var lightUniforms = light.__webglUniforms;
2598
				zlights.directional[ writeIndexDirectional ++ ] = lightUniforms;
M
Mr.doob 已提交
2599

2600
				if ( ! light.visible ) {
B
Ben Houston 已提交
2601
					lightUniforms.color.setRGB( 0, 0, 0 );
2602 2603
					continue;
				}
M
Mr.doob 已提交
2604

2605
				lightUniforms.direction.setFromMatrixPosition( light.matrixWorld );
2606
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
2607 2608
				lightUniforms.direction.sub( _vector3 );
				lightUniforms.direction.transformDirection( viewMatrix );
M
Mr.doob 已提交
2609

B
Ben Houston 已提交
2610
				lightUniforms.color.copy( light.color ).multiplyScalar( light.intensity );
M
Mr.doob 已提交
2611 2612 2613

			} else if ( light instanceof THREE.PointLight ) {

B
Ben Houston 已提交
2614 2615 2616 2617 2618 2619 2620 2621
				if( ! light.__webglUniforms ) {
					light.__webglUniforms = {
						position: new THREE.Vector3(),
						color: new THREE.Color(),
						distance: 0,
						decay: 0
					}
				}
M
Mr.doob 已提交
2622

B
Ben Houston 已提交
2623
				var lightUniforms = light.__webglUniforms;
2624
				zlights.point[ writeIndexPoint ++ ] = lightUniforms; 
M
Mr.doob 已提交
2625

B
Ben Houston 已提交
2626 2627 2628 2629
				if ( ! light.visible ) {
					lightUniforms.color.setRGB( 0, 0, 0 );
					continue;
				}
M
Mr.doob 已提交
2630

2631 2632
				lightUniforms.position.setFromMatrixPosition( light.matrixWorld );
				lightUniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2633

B
Ben Houston 已提交
2634 2635
				lightUniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				lightUniforms.distance = light.distance;
B
Ben Houston 已提交
2636
				lightUniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2637 2638 2639

			} else if ( light instanceof THREE.SpotLight ) {

B
Ben Houston 已提交
2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
				if( ! light.__webglUniforms ) {
					light.__webglUniforms = {
						position: new THREE.Vector3(),
						direction: new THREE.Vector3(),
						color: new THREE.Color(),
						distance: 0,
						decay: 0,
						angleCos: 0
					}
				}
M
Mr.doob 已提交
2650

B
Ben Houston 已提交
2651
				var lightUniforms = light.__webglUniforms;
2652
				zlights.spot[ writeIndexSpot ++ ] = lightUniforms; 
M
Mr.doob 已提交
2653

B
Ben Houston 已提交
2654 2655 2656 2657
				if ( ! light.visible ) {
					lightUniforms.color.setRGB( 0, 0, 0 );
					continue;
				}
M
Mr.doob 已提交
2658

2659 2660
				lightUniforms.position.setFromMatrixPosition( light.matrixWorld );
				lightUniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2661

B
Ben Houston 已提交
2662 2663
				lightUniforms.color.copy( color ).multiplyScalar( intensity );
				lightUniforms.distance = distance;
M
Mr.doob 已提交
2664

2665
				lightUniforms.direction.setFromMatrixPosition( light.matrixWorld );
2666
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
2667 2668
				lightUniforms.direction.sub( _vector3 );
				lightUniforms.direction.transformDirection( viewMatrix );
M
Mr.doob 已提交
2669

B
Ben Houston 已提交
2670 2671 2672
				lightUniforms.angleCos = Math.cos( light.angle );
				lightUniforms.exponent = light.exponent;
				lightUniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2673 2674 2675

			} else if ( light instanceof THREE.HemisphereLight ) {

B
Ben Houston 已提交
2676 2677
				if( ! light.__webglUniforms ) {
					light.__webglUniforms = {
2678
						direction: new THREE.Vector3(),
B
Ben Houston 已提交
2679 2680 2681 2682
						skyColor: new THREE.Color(),
						groundColor: new THREE.Color()
					}
				}
M
Mr.doob 已提交
2683

B
Ben Houston 已提交
2684
				var lightUniforms = light.__webglUniforms;
2685
				zlights.hemi[ writeIndexHemi ++ ] = lightUniforms; 
M
Mr.doob 已提交
2686

B
Ben Houston 已提交
2687 2688 2689 2690
				if ( ! light.visible ) {
					lightUniforms.skyColor.setRGB( 0, 0, 0 );
					continue;
				}
M
Mr.doob 已提交
2691

2692 2693 2694
				lightUniforms.direction.setFromMatrixPosition( light.matrixWorld );
				lightUniforms.direction.transformDirection( viewMatrix );
				lightUniforms.direction.normalize();
M
Mr.doob 已提交
2695

2696
				lightUniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
B
Ben Houston 已提交
2697
				lightUniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
M
Mr.doob 已提交
2698 2699 2700 2701 2702 2703 2704 2705 2706

			}

		}

		zlights.ambient[ 0 ] = r;
		zlights.ambient[ 1 ] = g;
		zlights.ambient[ 2 ] = b;

2707 2708 2709 2710 2711
		zlights.directional.length = writeIndexDirectional;
		zlights.point.length = writeIndexPoint;
		zlights.spot.length = writeIndexSpot;
		zlights.hemi.length = writeIndexHemi;

M
Mr.doob 已提交
2712
	}
M
Mr.doob 已提交
2713 2714 2715 2716 2717 2718 2719

	// GL state setting

	this.setFaceCulling = function ( cullFace, frontFaceDirection ) {

		if ( cullFace === THREE.CullFaceNone ) {

2720
			state.disable( _gl.CULL_FACE );
M
Mr.doob 已提交
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747

		} else {

			if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {

				_gl.frontFace( _gl.CW );

			} else {

				_gl.frontFace( _gl.CCW );

			}

			if ( cullFace === THREE.CullFaceBack ) {

				_gl.cullFace( _gl.BACK );

			} else if ( cullFace === THREE.CullFaceFront ) {

				_gl.cullFace( _gl.FRONT );

			} else {

				_gl.cullFace( _gl.FRONT_AND_BACK );

			}

2748
			state.enable( _gl.CULL_FACE );
M
Mr.doob 已提交
2749 2750 2751 2752 2753 2754 2755 2756 2757

		}

	};

	// Textures

	function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {

2758 2759
		var extension;

M
Mr.doob 已提交
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
		if ( isImagePowerOfTwo ) {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );

		} else {

			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
			_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
M
Mr.doob 已提交
2772 2773 2774

			if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {

M
Mr.doob 已提交
2775
				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
M
Mr.doob 已提交
2776

2777
			}
M
Mr.doob 已提交
2778 2779 2780 2781

			_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
			_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );

M
Mr.doob 已提交
2782 2783
			if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {

M
Mr.doob 已提交
2784
				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
M
Mr.doob 已提交
2785

2786
			}
M
Mr.doob 已提交
2787

M
Mr.doob 已提交
2788 2789
		}

2790 2791
		extension = extensions.get( 'EXT_texture_filter_anisotropic' );

2792
		if ( extension ) {
M
Mr.doob 已提交
2793

2794 2795
			if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
			if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
M
Mr.doob 已提交
2796

2797
			if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
M
Mr.doob 已提交
2798

2799
				_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
2800
				properties.get( texture ).__currentAnisotropy = texture.anisotropy;
M
Mr.doob 已提交
2801 2802 2803 2804 2805

			}

		}

M
Mr.doob 已提交
2806
	}
M
Mr.doob 已提交
2807

2808
	function uploadTexture( textureProperties, texture, slot ) {
2809

2810
		if ( textureProperties.__webglInit === undefined ) {
2811

2812
			textureProperties.__webglInit = true;
2813 2814 2815

			texture.addEventListener( 'dispose', onTextureDispose );

2816
			textureProperties.__webglTexture = _gl.createTexture();
2817

2818
			_infoMemory.textures ++;
2819 2820

		}
M
Mr.doob 已提交
2821

B
Ben Adams 已提交
2822
		state.activeTexture( _gl.TEXTURE0 + slot );
2823
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
M
Mr.doob 已提交
2824

H
Henri Astre 已提交
2825 2826 2827 2828
		_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
		_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
		_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );

G
gero3 已提交
2829
		texture.image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
2830

M
Mr.doob 已提交
2831 2832 2833 2834 2835 2836
		if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false ) {

			texture.image = makePowerOfTwo( texture.image );

		}

H
Henri Astre 已提交
2837
		var image = texture.image,
M
Mr.doob 已提交
2838
		isImagePowerOfTwo = isPowerOfTwo( image ),
H
Henri Astre 已提交
2839 2840
		glFormat = paramThreeToGL( texture.format ),
		glType = paramThreeToGL( texture.type );
M
Mr.doob 已提交
2841

H
Henri Astre 已提交
2842
		setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
M
Mr.doob 已提交
2843

H
Henri Astre 已提交
2844
		var mipmap, mipmaps = texture.mipmaps;
M
Mr.doob 已提交
2845

H
Henri Astre 已提交
2846
		if ( texture instanceof THREE.DataTexture ) {
M
Mr.doob 已提交
2847

H
Henri Astre 已提交
2848 2849 2850
			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels
M
Mr.doob 已提交
2851

H
Henri Astre 已提交
2852 2853 2854
			if ( mipmaps.length > 0 && isImagePowerOfTwo ) {

				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2855

H
Henri Astre 已提交
2856
					mipmap = mipmaps[ i ];
2857
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
2858

H
Henri Astre 已提交
2859
				}
M
Mr.doob 已提交
2860

H
Henri Astre 已提交
2861
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2862

H
Henri Astre 已提交
2863
			} else {
M
Mr.doob 已提交
2864

2865
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
M
Mr.doob 已提交
2866

H
Henri Astre 已提交
2867
			}
M
Mr.doob 已提交
2868

H
Henri Astre 已提交
2869
		} else if ( texture instanceof THREE.CompressedTexture ) {
M
Mr.doob 已提交
2870

H
Henri Astre 已提交
2871
			for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2872

H
Henri Astre 已提交
2873
				mipmap = mipmaps[ i ];
M
Mr.doob 已提交
2874

2875
				if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
M
Mr.doob 已提交
2876

2877
					if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
M
Mr.doob 已提交
2878

2879
						state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
M
Mr.doob 已提交
2880

2881
					} else {
M
Mr.doob 已提交
2882

2883
						console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
M
Mr.doob 已提交
2884

2885
					}
M
Mr.doob 已提交
2886

H
Henri Astre 已提交
2887
				} else {
M
Mr.doob 已提交
2888

2889
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
2890

M
Mr.doob 已提交
2891 2892
				}

H
Henri Astre 已提交
2893 2894
			}

G
gero3 已提交
2895 2896 2897
		} else {

			// regular Texture (image, video, canvas)
H
Henri Astre 已提交
2898 2899 2900 2901 2902 2903

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
M
Mr.doob 已提交
2904

2905
				for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
M
Mr.doob 已提交
2906 2907

					mipmap = mipmaps[ i ];
2908
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
M
Mr.doob 已提交
2909 2910 2911

				}

H
Henri Astre 已提交
2912
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2913

H
Henri Astre 已提交
2914
			} else {
M
Mr.doob 已提交
2915

2916
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
M
Mr.doob 已提交
2917

H
Henri Astre 已提交
2918
			}
M
Mr.doob 已提交
2919

H
Henri Astre 已提交
2920
		}
M
Mr.doob 已提交
2921

H
Henri Astre 已提交
2922
		if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
M
Mr.doob 已提交
2923

2924
		textureProperties.__version = texture.version;
M
Mr.doob 已提交
2925

B
Ben Adams 已提交
2926
		if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
2927

2928
	}
M
Mr.doob 已提交
2929

H
Henri Astre 已提交
2930
	this.setTexture = function ( texture, slot ) {
M
Mr.doob 已提交
2931

2932 2933 2934
		var textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
M
Mr.doob 已提交
2935

2936
			var image = texture.image;
M
Mr.doob 已提交
2937

2938 2939
			if ( image === undefined ) {

2940
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
2941 2942 2943 2944
				return;

			}

2945
			if ( image.complete === false ) {
M
Mr.doob 已提交
2946

2947
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
2948 2949 2950 2951
				return;

			}

2952
			uploadTexture( textureProperties, texture, slot );
2953

2954
			return;
M
Mr.doob 已提交
2955 2956 2957

		}

B
Ben Adams 已提交
2958
		state.activeTexture( _gl.TEXTURE0 + slot );
2959
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
2960

M
Mr.doob 已提交
2961 2962 2963 2964
	};

	function clampToMaxSize ( image, maxSize ) {

2965
		if ( image.width > maxSize || image.height > maxSize ) {
M
Mr.doob 已提交
2966

2967 2968
			// Warning: Scaling through the canvas will only work with images that use
			// premultiplied alpha.
M
Mr.doob 已提交
2969

2970
			var scale = maxSize / Math.max( image.width, image.height );
M
Mr.doob 已提交
2971

2972 2973 2974
			var canvas = document.createElement( 'canvas' );
			canvas.width = Math.floor( image.width * scale );
			canvas.height = Math.floor( image.height * scale );
M
Mr.doob 已提交
2975

2976 2977
			var context = canvas.getContext( '2d' );
			context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
M
Mr.doob 已提交
2978

2979
			console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
M
Mr.doob 已提交
2980

2981 2982 2983
			return canvas;

		}
M
Mr.doob 已提交
2984

2985
		return image;
M
Mr.doob 已提交
2986 2987 2988

	}

M
Mr.doob 已提交
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
	function isPowerOfTwo( image ) {

		return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );

	}

	function textureNeedsPowerOfTwo( texture ) {

		if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
		if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;

		return false;

	}

	function makePowerOfTwo( image ) {

		if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {

			var canvas = document.createElement( 'canvas' );
			canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
			canvas.height = THREE.Math.nearestPowerOfTwo( image.height );

			var context = canvas.getContext( '2d' );
			context.drawImage( image, 0, 0, canvas.width, canvas.height );

			console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );

			return canvas;

		}

		return image;

	}

M
Mr.doob 已提交
3025 3026
	function setCubeTexture ( texture, slot ) {

3027
		var textureProperties = properties.get( texture );
3028

M
Mr.doob 已提交
3029 3030
		if ( texture.image.length === 6 ) {

3031
			if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
M
Mr.doob 已提交
3032

3033
				if ( ! textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
3034

3035 3036
					texture.addEventListener( 'dispose', onTextureDispose );

3037
					textureProperties.__image__webglTextureCube = _gl.createTexture();
M
Mr.doob 已提交
3038

3039
					_infoMemory.textures ++;
M
Mr.doob 已提交
3040 3041 3042

				}

B
Ben Adams 已提交
3043
				state.activeTexture( _gl.TEXTURE0 + slot );
3044
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
3045 3046 3047

				_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );

M
Mr.doob 已提交
3048 3049
				var isCompressed = texture instanceof THREE.CompressedTexture;
				var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
M
Mr.doob 已提交
3050 3051 3052 3053 3054

				var cubeImage = [];

				for ( var i = 0; i < 6; i ++ ) {

3055
					if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
M
Mr.doob 已提交
3056

G
gero3 已提交
3057
						cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
M
Mr.doob 已提交
3058 3059 3060

					} else {

3061
						cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
M
Mr.doob 已提交
3062 3063 3064 3065 3066 3067

					}

				}

				var image = cubeImage[ 0 ],
M
Mr.doob 已提交
3068
				isImagePowerOfTwo = isPowerOfTwo( image ),
M
Mr.doob 已提交
3069 3070 3071 3072 3073 3074 3075
				glFormat = paramThreeToGL( texture.format ),
				glType = paramThreeToGL( texture.type );

				setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );

				for ( var i = 0; i < 6; i ++ ) {

3076
					if ( ! isCompressed ) {
M
Mr.doob 已提交
3077

M
Mr.doob 已提交
3078
						if ( isDataTexture ) {
3079

3080
							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
3081

M
Mr.doob 已提交
3082
						} else {
3083

3084
							state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
3085

M
Mr.doob 已提交
3086 3087
						}

3088
					} else {
3089

M
Mr.doob 已提交
3090 3091
						var mipmap, mipmaps = cubeImage[ i ].mipmaps;

3092
						for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
M
Mr.doob 已提交
3093 3094

							mipmap = mipmaps[ j ];
M
Mr.doob 已提交
3095

3096
							if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
M
Mr.doob 已提交
3097

3098
								if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
M
Mr.doob 已提交
3099

3100
									state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
M
Mr.doob 已提交
3101

3102
								} else {
M
Mr.doob 已提交
3103

3104
									console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
M
Mr.doob 已提交
3105

3106
								}
M
Mr.doob 已提交
3107

3108
							} else {
M
Mr.doob 已提交
3109

3110
								state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
M
Mr.doob 已提交
3111

3112
							}
M
Mr.doob 已提交
3113

3114
						}
M
Mr.doob 已提交
3115

M
Mr.doob 已提交
3116
					}
M
Mr.doob 已提交
3117

M
Mr.doob 已提交
3118 3119 3120 3121 3122 3123 3124 3125
				}

				if ( texture.generateMipmaps && isImagePowerOfTwo ) {

					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

				}

3126
				textureProperties.__version = texture.version;
M
Mr.doob 已提交
3127

B
Ben Adams 已提交
3128
				if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
3129 3130 3131

			} else {

B
Ben Adams 已提交
3132
				state.activeTexture( _gl.TEXTURE0 + slot );
3133
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
3134 3135 3136 3137 3138

			}

		}

M
Mr.doob 已提交
3139
	}
M
Mr.doob 已提交
3140 3141 3142

	function setCubeTextureDynamic ( texture, slot ) {

B
Ben Adams 已提交
3143
		state.activeTexture( _gl.TEXTURE0 + slot );
3144
		state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
M
Mr.doob 已提交
3145

M
Mr.doob 已提交
3146
	}
M
Mr.doob 已提交
3147 3148 3149 3150 3151 3152

	// Render targets

	function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {

		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
M
Mr.doob 已提交
3153
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
M
Mr.doob 已提交
3154

M
Mr.doob 已提交
3155
	}
M
Mr.doob 已提交
3156

M
Mr.doob 已提交
3157
	function setupRenderBuffer ( renderbuffer, renderTarget ) {
M
Mr.doob 已提交
3158 3159 3160 3161 3162 3163 3164 3165 3166

		_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );

		if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

		/* For some reason this is not working. Defaulting to RGBA4.
3167
		} else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
M
Mr.doob 已提交
3168 3169 3170 3171

			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
		*/
G
gero3 已提交
3172

M
Mr.doob 已提交
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183
		} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
			_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

		} else {

			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );

		}

M
Mr.doob 已提交
3184
	}
M
Mr.doob 已提交
3185 3186 3187 3188 3189

	this.setRenderTarget = function ( renderTarget ) {

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );

3190
		if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
M
Mr.doob 已提交
3191

3192
			var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
3193
			var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
3194 3195 3196 3197 3198 3199

			if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
			if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;

			renderTarget.addEventListener( 'dispose', onRenderTargetDispose );

M
Mr.doob 已提交
3200
			textureProperties.__webglTexture = _gl.createTexture();
M
Mr.doob 已提交
3201

3202
			_infoMemory.textures ++;
M
Mr.doob 已提交
3203 3204 3205

			// Setup texture, create render and frame buffers

M
Mr.doob 已提交
3206 3207 3208
			var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ),
				glFormat = paramThreeToGL( renderTarget.texture.format ),
				glType = paramThreeToGL( renderTarget.texture.type );
M
Mr.doob 已提交
3209 3210 3211

			if ( isCube ) {

3212 3213
				renderTargetProperties.__webglFramebuffer = [];
				renderTargetProperties.__webglRenderbuffer = [];
M
Mr.doob 已提交
3214

M
Mr.doob 已提交
3215
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
B
Ben Adams 已提交
3216

M
Mr.doob 已提交
3217
				setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
M
Mr.doob 已提交
3218 3219 3220

				for ( var i = 0; i < 6; i ++ ) {

3221 3222
					renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
					renderTargetProperties.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
3223
					state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
M
Mr.doob 已提交
3224

3225 3226
					setupFrameBuffer( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
					setupRenderBuffer( renderTargetProperties.__webglRenderbuffer[ i ], renderTarget );
M
Mr.doob 已提交
3227 3228 3229

				}

M
Mr.doob 已提交
3230
				if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
M
Mr.doob 已提交
3231 3232 3233

			} else {

3234
				renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
M
Mr.doob 已提交
3235 3236 3237

				if ( renderTarget.shareDepthFrom ) {

3238
					renderTargetProperties.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
M
Mr.doob 已提交
3239 3240 3241

				} else {

3242
					renderTargetProperties.__webglRenderbuffer = _gl.createRenderbuffer();
M
Mr.doob 已提交
3243 3244 3245

				}

M
Mr.doob 已提交
3246 3247
				state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
				setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
M
Mr.doob 已提交
3248

3249
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
M
Mr.doob 已提交
3250

3251
				setupFrameBuffer( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
M
Mr.doob 已提交
3252 3253 3254 3255 3256

				if ( renderTarget.shareDepthFrom ) {

					if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

3257
						_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
M
Mr.doob 已提交
3258 3259 3260

					} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

3261
						_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTargetProperties.__webglRenderbuffer );
M
Mr.doob 已提交
3262 3263 3264 3265 3266

					}

				} else {

3267
					setupRenderBuffer( renderTargetProperties.__webglRenderbuffer, renderTarget );
M
Mr.doob 已提交
3268 3269 3270

				}

M
Mr.doob 已提交
3271
				if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
M
Mr.doob 已提交
3272 3273 3274 3275 3276 3277 3278

			}

			// Release everything

			if ( isCube ) {

B
Ben Adams 已提交
3279
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
M
Mr.doob 已提交
3280 3281 3282

			} else {

B
Ben Adams 已提交
3283
				state.bindTexture( _gl.TEXTURE_2D, null );
M
Mr.doob 已提交
3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295

			}

			_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
			_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );

		}

		var framebuffer, width, height, vx, vy;

		if ( renderTarget ) {

3296
			var renderTargetProperties = properties.get( renderTarget );
F
Fordy 已提交
3297

M
Mr.doob 已提交
3298 3299
			if ( isCube ) {

3300
				framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
M
Mr.doob 已提交
3301 3302 3303

			} else {

3304
				framebuffer = renderTargetProperties.__webglFramebuffer;
M
Mr.doob 已提交
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334

			}

			width = renderTarget.width;
			height = renderTarget.height;

			vx = 0;
			vy = 0;

		} else {

			framebuffer = null;

			width = _viewportWidth;
			height = _viewportHeight;

			vx = _viewportX;
			vy = _viewportY;

		}

		if ( framebuffer !== _currentFramebuffer ) {

			_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
			_gl.viewport( vx, vy, width, height );

			_currentFramebuffer = framebuffer;

		}

M
Mr.doob 已提交
3335 3336 3337 3338 3339 3340 3341
		if ( isCube ) {

			var textureProperties = properties.get( renderTarget.texture );
			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, 0 );

		}

M
Mr.doob 已提交
3342 3343 3344 3345 3346
		_currentWidth = width;
		_currentHeight = height;

	};

M
Mr.doob 已提交
3347
	this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
3348

M
Mr.doob 已提交
3349
		if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
3350

3351
			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
G
gero3 已提交
3352
			return;
3353

G
gero3 已提交
3354
		}
3355

M
Mr.doob 已提交
3356
		var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
3357

M
Mr.doob 已提交
3358
		if ( framebuffer ) {
3359

G
gero3 已提交
3360
			var restore = false;
3361

M
Mr.doob 已提交
3362
			if ( framebuffer !== _currentFramebuffer ) {
3363

M
Mr.doob 已提交
3364
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
3365

G
gero3 已提交
3366
				restore = true;
3367

G
gero3 已提交
3368
			}
3369

M
Mr.doob 已提交
3370
			try {
3371

M
Mr.doob 已提交
3372
				var texture = renderTarget.texture;
3373

M
Mr.doob 已提交
3374 3375
				if ( texture.format !== THREE.RGBAFormat
					&& paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
3376

M
Mr.doob 已提交
3377 3378
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
					return;
3379

M
Mr.doob 已提交
3380
				}
3381

M
Mr.doob 已提交
3382 3383 3384 3385
				if ( texture.type !== THREE.UnsignedByteType
					&& paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE )
					&& ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) )
					&& ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
3386

M
Mr.doob 已提交
3387 3388
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
					return;
3389

M
Mr.doob 已提交
3390
				}
3391

M
Mr.doob 已提交
3392
				if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
3393

M
Mr.doob 已提交
3394
					_gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
3395

M
Mr.doob 已提交
3396
				} else {
M
Mr.doob 已提交
3397

M
Mr.doob 已提交
3398 3399 3400
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

				}
M
Mr.doob 已提交
3401

M
Mr.doob 已提交
3402
			} finally {
M
Mr.doob 已提交
3403

M
Mr.doob 已提交
3404 3405 3406
				if ( restore ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
M
Mr.doob 已提交
3407

M
Mr.doob 已提交
3408 3409 3410
				}

			}
M
Mr.doob 已提交
3411 3412 3413

		}

M
Mr.doob 已提交
3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
	};

	function updateRenderTargetMipmap( renderTarget ) {

		var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
		var texture = properties.get( renderTarget.texture ).__webglTexture;

		state.bindTexture( target, texture );
		_gl.generateMipmap( target );
		state.bindTexture( target, null );

M
Mr.doob 已提交
3425
	}
M
Mr.doob 已提交
3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438

	// Fallback filters for non-power-of-2 textures

	function filterFallback ( f ) {

		if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {

			return _gl.NEAREST;

		}

		return _gl.LINEAR;

M
Mr.doob 已提交
3439
	}
M
Mr.doob 已提交
3440 3441 3442 3443 3444

	// Map three.js constants to WebGL constants

	function paramThreeToGL ( p ) {

3445 3446
		var extension;

M
Mr.doob 已提交
3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
		if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
		if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
		if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;

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

		if ( p === THREE.LinearFilter ) return _gl.LINEAR;
		if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
		if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;

		if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
		if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
		if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
		if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;

		if ( p === THREE.ByteType ) return _gl.BYTE;
		if ( p === THREE.ShortType ) return _gl.SHORT;
		if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
		if ( p === THREE.IntType ) return _gl.INT;
		if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
		if ( p === THREE.FloatType ) return _gl.FLOAT;

3471 3472 3473 3474 3475 3476 3477 3478
		extension = extensions.get( 'OES_texture_half_float' );

		if ( extension !== null ) {

			if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;

		}

M
Mr.doob 已提交
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
		if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
		if ( p === THREE.RGBFormat ) return _gl.RGB;
		if ( p === THREE.RGBAFormat ) return _gl.RGBA;
		if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
		if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;

		if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
		if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
		if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;

		if ( p === THREE.ZeroFactor ) return _gl.ZERO;
		if ( p === THREE.OneFactor ) return _gl.ONE;
		if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
		if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
		if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
		if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
		if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
		if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;

		if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
		if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
		if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;

3502
		extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
M
Mr.doob 已提交
3503

3504 3505 3506 3507 3508 3509
		if ( extension !== null ) {

			if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
			if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
			if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
			if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
M
Mr.doob 已提交
3510 3511 3512

		}

3513 3514 3515
		extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

		if ( extension !== null ) {
P
Pierre Lepers 已提交
3516

3517 3518 3519 3520
			if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
			if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
			if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
			if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
P
Pierre Lepers 已提交
3521 3522 3523

		}

3524 3525 3526
		extension = extensions.get( 'EXT_blend_minmax' );

		if ( extension !== null ) {
3527

3528 3529
			if ( p === THREE.MinEquation ) return extension.MIN_EXT;
			if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
3530 3531 3532

		}

M
Mr.doob 已提交
3533 3534
		return 0;

M
Mr.doob 已提交
3535
	}
M
Mr.doob 已提交
3536 3537

};