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

THREE.WebGLRenderer = function ( parameters ) {

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

	parameters = parameters || {};

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

18
	_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
19
	_depth = parameters.depth !== undefined ? parameters.depth : true,
M
Mr.doob 已提交
20
	_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
21 22
	_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
	_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
M
Mr.doob 已提交
23
	_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
M
Mr.doob 已提交
24

M
Mr.doob 已提交
25
	var lights = [];
M
Mr.doob 已提交
26

O
OpenShift guest 已提交
27
	var opaqueObjects = [];
M
Mr.doob 已提交
28
	var opaqueObjectsLastIndex = - 1;
29
	var transparentObjects = [];
M
Mr.doob 已提交
30
	var transparentObjectsLastIndex = - 1;
31

32 33
	var morphInfluences = new Float32Array( 8 );

M
Mr.doob 已提交
34 35 36
	var sprites = [];
	var lensFlares = [];

M
Mr.doob 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
	// 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;

T
tschw 已提交
53 54 55 56 57
	// user-defined clipping

	this.clippingPlanes = [];
	this.localClippingEnabled = false;

M
Mr.doob 已提交
58 59
	// physically based shading

60
	this.gammaFactor = 2.0;	// for backwards compatibility
M
Mr.doob 已提交
61 62 63
	this.gammaInput = false;
	this.gammaOutput = false;

64 65
	// physical lights

66
	this.physicallyCorrectLights = false;
67

B
Ben Houston 已提交
68 69 70 71 72 73
	// tone mapping

	this.toneMapping = THREE.LinearToneMapping;
	this.toneMappingExposure = 1.0;
	this.toneMappingWhitePoint = 1.0;

M
Mr.doob 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
	// morphs

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

	// flags

	this.autoScaleCubemaps = true;

	// internal properties

	var _this = this,

	// internal state cache

	_currentProgram = null,
90
	_currentRenderTarget = null,
M
Mr.doob 已提交
91
	_currentFramebuffer = null,
92
	_currentMaterialId = - 1,
93
	_currentGeometryProgram = '',
M
Mr.doob 已提交
94 95
	_currentCamera = null,

96 97 98 99 100
	_currentScissor = new THREE.Vector4(),
	_currentScissorTest = null,

	_currentViewport = new THREE.Vector4(),

101 102
	//

M
Mr.doob 已提交
103 104
	_usedTextureUnits = 0,

M
Mr.doob 已提交
105 106 107 108 109 110 111 112 113 114 115
	//

	_clearColor = new THREE.Color( 0x000000 ),
	_clearAlpha = 0,

	_width = _canvas.width,
	_height = _canvas.height,

	_pixelRatio = 1,

	_scissor = new THREE.Vector4( 0, 0, _width, _height ),
116 117
	_scissorTest = false,

M
Mr.doob 已提交
118
	_viewport = new THREE.Vector4( 0, 0, _width, _height ),
119

M
Mr.doob 已提交
120 121 122 123
	// frustum

	_frustum = new THREE.Frustum(),

T
tschw 已提交
124 125
	// clipping

T
tschw 已提交
126
	_clipping = new THREE.WebGLClipping(),
T
tschw 已提交
127 128 129 130 131
	_clippingEnabled = false,
	_localClippingEnabled = false,

	_sphere = new THREE.Sphere(),

M
Mr.doob 已提交
132
	// camera matrices cache
M
Mr.doob 已提交
133 134 135 136 137 138 139 140 141

	_projScreenMatrix = new THREE.Matrix4(),

	_vector3 = new THREE.Vector3(),

	// light arrays cache

	_lights = {

142 143
		hash: '',

M
Mr.doob 已提交
144
		ambient: [ 0, 0, 0 ],
M
Mr.doob 已提交
145
		directional: [],
146 147
		directionalShadowMap: [],
		directionalShadowMatrix: [],
M
Mr.doob 已提交
148
		spot: [],
149 150
		spotShadowMap: [],
		spotShadowMatrix: [],
M
Mr.doob 已提交
151
		point: [],
152 153
		pointShadowMap: [],
		pointShadowMatrix: [],
154 155
		hemi: [],

156
		shadows: []
M
Mr.doob 已提交
157

158 159
	},

M
Mr.doob 已提交
160 161
	// info

162
	_infoMemory = {
163 164

		geometries: 0,
T
tschw 已提交
165
		textures: 0
166 167 168

	},

169
	_infoRender = {
170 171 172 173 174 175

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

M
Mr.doob 已提交
176 177
	};

M
Mr.doob 已提交
178
	this.info = {
179

M
Mr.doob 已提交
180 181
		render: _infoRender,
		memory: _infoMemory,
182
		programs: null
M
Mr.doob 已提交
183 184

	};
185

186

M
Mr.doob 已提交
187 188 189 190
	// initialize

	var _gl;

M
Mr.doob 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
	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 已提交
206
			if ( _canvas.getContext( 'webgl' ) !== null ) {
207 208 209 210 211 212 213 214

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

			} else {

				throw 'Error creating WebGL context.';

			}
M
Mr.doob 已提交
215 216 217

		}

218 219 220 221 222 223 224 225 226 227 228 229
		// Some experimental-webgl implementations do not have getShaderPrecisionFormat

		if ( _gl.getShaderPrecisionFormat === undefined ) {

			_gl.getShaderPrecisionFormat = function () {

				return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };

			};

		}

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

M
Mr.doob 已提交
232 233
	} catch ( error ) {

234
		console.error( 'THREE.WebGLRenderer: ' + error );
M
Mr.doob 已提交
235 236 237

	}

238
	var _isWebGL2 = (typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext);
239 240
	var extensions = new THREE.WebGLExtensions( _gl );

241
	extensions.get( 'WEBGL_depth_texture' );
242 243
	extensions.get( 'OES_texture_float' );
	extensions.get( 'OES_texture_float_linear' );
244 245
	extensions.get( 'OES_texture_half_float' );
	extensions.get( 'OES_texture_half_float_linear' );
246
	extensions.get( 'OES_standard_derivatives' );
B
Ben Adams 已提交
247
	extensions.get( 'ANGLE_instanced_arrays' );
248

249 250
	if ( extensions.get( 'OES_element_index_uint' ) ) {

251
		THREE.BufferGeometry.MaxIndex = 4294967296;
252 253 254

	}

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

257 258 259
	var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
	var properties = new THREE.WebGLProperties();
	var objects = new THREE.WebGLObjects( _gl, properties, this.info );
G
gero3 已提交
260
	var programCache = new THREE.WebGLPrograms( this, capabilities );
M
Mr.doob 已提交
261
	var lightCache = new THREE.WebGLLights();
262

263 264
	this.info.programs = programCache.programs;

265 266
	var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
	var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
267

M
Mr.doob 已提交
268 269
	//

270 271
	function getTargetPixelRatio() {

272
		return _currentRenderTarget === null ? _pixelRatio : 1;
273 274 275

	}

276
	function glClearColor( r, g, b, a ) {
277 278 279

		if ( _premultipliedAlpha === true ) {

280
			r *= a; g *= a; b *= a;
281 282 283

		}

M
Mr.doob 已提交
284
		state.clearColor( r, g, b, a );
285

286
	}
287

288
	function setDefaultGLState() {
M
Mr.doob 已提交
289

M
Mr.doob 已提交
290
		state.init();
M
Mr.doob 已提交
291

292 293
		state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
		state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
M
Mr.doob 已提交
294

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

297
	}
298

299
	function resetGLState() {
300 301 302 303

		_currentProgram = null;
		_currentCamera = null;

304
		_currentGeometryProgram = '';
305 306
		_currentMaterialId = - 1;

M
Mr.doob 已提交
307 308
		state.reset();

309
	}
M
Mr.doob 已提交
310 311 312 313

	setDefaultGLState();

	this.context = _gl;
M
Mr.doob 已提交
314
	this.capabilities = capabilities;
315
	this.extensions = extensions;
316
	this.properties = properties;
M
Mr.doob 已提交
317
	this.state = state;
M
Mr.doob 已提交
318

M
Mr.doob 已提交
319 320
	// shadow map

321
	var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
M
Mr.doob 已提交
322

323
	this.shadowMap = shadowMap;
M
Mr.doob 已提交
324

M
Mr.doob 已提交
325

M
Mr.doob 已提交
326 327 328 329 330
	// Plugins

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

M
Mr.doob 已提交
331 332 333 334 335 336 337 338
	// API

	this.getContext = function () {

		return _gl;

	};

339 340 341 342 343 344
	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

345 346 347 348 349 350
	this.forceContextLoss = function () {

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

	};

351
	this.getMaxAnisotropy = ( function () {
M
Mr.doob 已提交
352

353
		var value;
M
Mr.doob 已提交
354

355
		return function getMaxAnisotropy() {
356

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

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

M
Mr.doob 已提交
361
			if ( extension !== null ) {
362

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

M
Mr.doob 已提交
365 366 367 368 369
			} else {

				value = 0;

			}
370 371 372

			return value;

M
Mr.doob 已提交
373
		};
374 375

	} )();
M
Mr.doob 已提交
376 377 378

	this.getPrecision = function () {

G
gero3 已提交
379
		return capabilities.precision;
M
Mr.doob 已提交
380 381 382

	};

383 384
	this.getPixelRatio = function () {

385
		return _pixelRatio;
386 387 388 389 390

	};

	this.setPixelRatio = function ( value ) {

391 392 393 394 395
		if ( value === undefined ) return;

		_pixelRatio = value;

		this.setSize( _viewport.z, _viewport.w, false );
396 397 398

	};

399 400 401
	this.getSize = function () {

		return {
402 403
			width: _width,
			height: _height
404 405 406 407
		};

	};

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

410 411 412
		_width = width;
		_height = height;

413 414
		_canvas.width = width * _pixelRatio;
		_canvas.height = height * _pixelRatio;
415

416
		if ( updateStyle !== false ) {
417

G
gero3 已提交
418 419
			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';
420

G
gero3 已提交
421
		}
M
Mr.doob 已提交
422

423
		this.setViewport( 0, 0, width, height );
M
Mr.doob 已提交
424 425 426 427 428

	};

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

429
		state.viewport( _viewport.set( x, y, width, height ) );
M
Mr.doob 已提交
430 431 432

	};

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

435
		state.scissor( _scissor.set( x, y, width, height ) );
M
Mr.doob 已提交
436 437 438

	};

439 440
	this.setScissorTest = function ( boolean ) {

441
		state.setScissorTest( _scissorTest = boolean );
M
Mr.doob 已提交
442 443 444 445 446

	};

	// Clearing

M
Mr.doob 已提交
447
	this.getClearColor = function () {
M
Mr.doob 已提交
448

M
Mr.doob 已提交
449
		return _clearColor;
M
Mr.doob 已提交
450 451 452

	};

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

M
Mr.doob 已提交
455
		_clearColor.set( color );
456

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

459
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
460 461 462

	};

M
Mr.doob 已提交
463
	this.getClearAlpha = function () {
M
Mr.doob 已提交
464

M
Mr.doob 已提交
465
		return _clearAlpha;
M
Mr.doob 已提交
466 467 468

	};

M
Mr.doob 已提交
469
	this.setClearAlpha = function ( alpha ) {
M
Mr.doob 已提交
470

M
Mr.doob 已提交
471
		_clearAlpha = alpha;
M
Mr.doob 已提交
472

473
		glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
M
Mr.doob 已提交
474 475 476 477 478 479 480 481 482 483 484 485

	};

	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 );
486 487 488 489 490

	};

	this.clearColor = function () {

M
Mr.doob 已提交
491
		this.clear( true, false, false );
492 493 494 495 496

	};

	this.clearDepth = function () {

M
Mr.doob 已提交
497
		this.clear( false, true, false );
498 499 500 501 502

	};

	this.clearStencil = function () {

M
Mr.doob 已提交
503
		this.clear( false, false, true );
M
Mr.doob 已提交
504 505 506 507 508 509 510 511 512 513

	};

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

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

	};

M
Mr.doob 已提交
514 515
	// Reset

516
	this.resetGLState = resetGLState;
M
Mr.doob 已提交
517

D
dubejf 已提交
518 519 520 521 522 523
	this.dispose = function() {

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

	};

M
Mr.doob 已提交
524
	// Events
M
Mr.doob 已提交
525

D
dubejf 已提交
526 527 528 529 530 531 532 533 534
	function onContextLost( event ) {

		event.preventDefault();

		resetGLState();
		setDefaultGLState();

		properties.clear();

M
Mr.doob 已提交
535
	}
D
dubejf 已提交
536

537
	function onTextureDispose( event ) {
M
Mr.doob 已提交
538 539 540 541 542 543 544

		var texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

545
		_infoMemory.textures --;
M
Mr.doob 已提交
546 547


548
	}
M
Mr.doob 已提交
549

550
	function onRenderTargetDispose( event ) {
M
Mr.doob 已提交
551 552 553 554 555 556 557

		var renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

558
		_infoMemory.textures --;
M
Mr.doob 已提交
559

560
	}
M
Mr.doob 已提交
561

562
	function onMaterialDispose( event ) {
M
Mr.doob 已提交
563 564 565 566 567 568 569

		var material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

570
	}
M
Mr.doob 已提交
571 572 573

	// Buffer deallocation

574
	function deallocateTexture( texture ) {
M
Mr.doob 已提交
575

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

578
		if ( texture.image && textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
579 580 581

			// cube texture

582
			_gl.deleteTexture( textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
583

584 585 586 587
		} else {

			// 2D texture

588
			if ( textureProperties.__webglInit === undefined ) return;
589

590
			_gl.deleteTexture( textureProperties.__webglTexture );
591

M
Mr.doob 已提交
592 593
		}

594
		// remove all webgl properties
595
		properties.delete( texture );
596

597
	}
M
Mr.doob 已提交
598

599
	function deallocateRenderTarget( renderTarget ) {
M
Mr.doob 已提交
600

601
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
602
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
603

604
		if ( ! renderTarget ) return;
M
Mr.doob 已提交
605

606 607 608 609 610 611 612 613 614 615 616
		if ( textureProperties.__webglTexture !== undefined ) {

			_gl.deleteTexture( textureProperties.__webglTexture );

		}

		if ( renderTarget.depthTexture ) {

			renderTarget.depthTexture.dispose();

		}
M
Mr.doob 已提交
617

M
Mr.doob 已提交
618 619 620 621
		if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

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

622
				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
623
				if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
M
Mr.doob 已提交
624 625 626 627 628

			}

		} else {

629
			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
630
			if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
M
Mr.doob 已提交
631 632 633

		}

M
Mr.doob 已提交
634
		properties.delete( renderTarget.texture );
D
Daosheng Mu 已提交
635
		properties.delete( renderTarget );
M
Mr.doob 已提交
636

637
	}
M
Mr.doob 已提交
638

639
	function deallocateMaterial( material ) {
M
Mr.doob 已提交
640

641 642 643 644
		releaseMaterialProgramReference( material );

		properties.delete( material );

645
	}
646 647


648
	function releaseMaterialProgramReference( material ) {
649

650
		var programInfo = properties.get( material ).program;
M
Mr.doob 已提交
651 652 653

		material.program = undefined;

654
		if ( programInfo !== undefined ) {
M
Mr.doob 已提交
655

656
			programCache.releaseProgram( programInfo );
M
Mr.doob 已提交
657

M
Mr.doob 已提交
658 659
		}

660
	}
M
Mr.doob 已提交
661 662 663 664 665

	// Buffer rendering

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

666
		state.initAttributes();
667

668
		var buffers = properties.get( object );
669

670 671 672 673
		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 已提交
674

675
		var attributes = program.getAttributes();
676

M
Mr.doob 已提交
677 678
		if ( object.hasPositions ) {

679
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
M
Mr.doob 已提交
680
			_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
681

682 683
			state.enableAttribute( attributes.position );
			_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
684 685 686 687 688

		}

		if ( object.hasNormals ) {

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

W
WestLangley 已提交
691
			if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
M
Mr.doob 已提交
692

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

695
					var array = object.normalArray;
M
Mr.doob 已提交
696

697 698 699
					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 已提交
700

701 702 703
					array[ i + 0 ] = nx;
					array[ i + 1 ] = ny;
					array[ i + 2 ] = nz;
M
Mr.doob 已提交
704

705 706 707
					array[ i + 3 ] = nx;
					array[ i + 4 ] = ny;
					array[ i + 5 ] = nz;
M
Mr.doob 已提交
708

709 710 711
					array[ i + 6 ] = nx;
					array[ i + 7 ] = ny;
					array[ i + 8 ] = nz;
M
Mr.doob 已提交
712 713 714 715 716 717

				}

			}

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

719
			state.enableAttribute( attributes.normal );
720

721
			_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
722 723 724 725 726

		}

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

727
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
M
Mr.doob 已提交
728
			_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
729

730
			state.enableAttribute( attributes.uv );
731

732
			_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
733 734 735 736 737

		}

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

738
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
M
Mr.doob 已提交
739
			_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
740

741
			state.enableAttribute( attributes.color );
742

743
			_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
744 745 746

		}

747
		state.disableUnusedAttributes();
748

M
Mr.doob 已提交
749 750 751 752 753 754
		_gl.drawArrays( _gl.TRIANGLES, 0, object.count );

		object.count = 0;

	};

755
	this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
756

M
Mr.doob 已提交
757 758
		setMaterial( material );

759
		var program = setProgram( camera, fog, material, object );
M
Mr.doob 已提交
760

M
Mr.doob 已提交
761 762
		var updateBuffers = false;
		var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
M
Mr.doob 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785

		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 ] );

			}

786
			activeInfluences.sort( absNumericalSort );
M
Mr.doob 已提交
787 788 789 790 791 792 793

			if ( activeInfluences.length > 8 ) {

				activeInfluences.length = 8;

			}

794 795
			var morphAttributes = geometry.morphAttributes;

M
Mr.doob 已提交
796 797 798 799 800 801 802
			for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {

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

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

803
					var index = influence[ 1 ];
M
Mr.doob 已提交
804

805 806
					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 已提交
807 808 809

				} else {

810 811
					if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
					if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
M
Mr.doob 已提交
812 813 814 815 816

				}

			}

T
tschw 已提交
817 818
			program.getUniforms().setValue(
					_gl, 'morphTargetInfluences', morphInfluences );
M
Mr.doob 已提交
819 820 821 822 823

			updateBuffers = true;

		}

824 825
		//

826
		var index = geometry.index;
827 828
		var position = geometry.attributes.position;

829 830
		if ( material.wireframe === true ) {

831
			index = objects.getWireframeAttribute( geometry );
832 833 834

		}

835 836
		var renderer;

837
		if ( index !== null ) {
838

839 840
			renderer = indexedBufferRenderer;
			renderer.setIndex( index );
841

842
		} else {
843

844
			renderer = bufferRenderer;
845

846
		}
M
Mr.doob 已提交
847

848
		if ( updateBuffers ) {
M
Mr.doob 已提交
849

850
			setupVertexAttributes( material, program, geometry );
M
Mr.doob 已提交
851

852
			if ( index !== null ) {
853

854
				_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
855 856 857

			}

858
		}
859

860 861
		//

M
Mr.doob 已提交
862 863
		var dataStart = 0;
		var dataCount = Infinity;
864

M
Mr.doob 已提交
865
		if ( index !== null ) {
866

M
Mr.doob 已提交
867
			dataCount = index.count;
868

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

M
Mr.doob 已提交
871
			dataCount = position.count;
872

M
Mr.doob 已提交
873
		}
874

M
Mr.doob 已提交
875 876
		var rangeStart = geometry.drawRange.start;
		var rangeCount = geometry.drawRange.count;
877

M
Mr.doob 已提交
878 879
		var groupStart = group !== null ? group.start : 0;
		var groupCount = group !== null ? group.count : Infinity;
880

M
Mr.doob 已提交
881 882 883 884 885 886
		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 );

		//
887

888
		if ( object instanceof THREE.Mesh ) {
889

890
			if ( material.wireframe === true ) {
891

892
				state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
893
				renderer.setMode( _gl.LINES );
894

895
			} else {
M
Mr.doob 已提交
896 897

				switch ( object.drawMode ) {
898

B
Ben Adams 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911
					case THREE.TrianglesDrawMode:
						renderer.setMode( _gl.TRIANGLES );
						break;

					case THREE.TriangleStripDrawMode:
						renderer.setMode( _gl.TRIANGLE_STRIP );
						break;

					case THREE.TriangleFanDrawMode:
						renderer.setMode( _gl.TRIANGLE_FAN );
						break;

				}
912

913
			}
914

915

916
		} else if ( object instanceof THREE.Line ) {
917

918
			var lineWidth = material.linewidth;
919

920
			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
921

922
			state.setLineWidth( lineWidth * getTargetPixelRatio() );
923

924
			if ( object instanceof THREE.LineSegments ) {
925

926
				renderer.setMode( _gl.LINES );
927

928
			} else {
929

930
				renderer.setMode( _gl.LINE_STRIP );
931 932

			}
M
Mr.doob 已提交
933

934
		} else if ( object instanceof THREE.Points ) {
935 936

			renderer.setMode( _gl.POINTS );
937 938

		}
939

J
jfranc 已提交
940
		if ( geometry instanceof THREE.InstancedBufferGeometry ) {
M
Mr.doob 已提交
941 942 943

			if ( geometry.maxInstancedCount > 0 ) {

J
jfranc 已提交
944
				renderer.renderInstances( geometry, drawStart, drawCount );
M
Mr.doob 已提交
945

J
jfranc 已提交
946
			}
947 948 949

		} else {

M
Mr.doob 已提交
950
			renderer.render( drawStart, drawCount );
951

M
Mr.doob 已提交
952 953 954 955
		}

	};

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

M
Mr.doob 已提交
958
		var extension;
B
Ben Adams 已提交
959

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

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

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

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

M
Mr.doob 已提交
969 970 971
			}

		}
B
Ben Adams 已提交
972

973 974
		if ( startIndex === undefined ) startIndex = 0;

975 976
		state.initAttributes();

977
		var geometryAttributes = geometry.attributes;
978

979
		var programAttributes = program.getAttributes();
980

981
		var materialDefaultAttributeValues = material.defaultAttributeValues;
982

983
		for ( var name in programAttributes ) {
984

985
			var programAttribute = programAttributes[ name ];
M
Mr.doob 已提交
986

M
Mr.doob 已提交
987
			if ( programAttribute >= 0 ) {
M
Mr.doob 已提交
988

989
				var geometryAttribute = geometryAttributes[ name ];
990

M
Mr.doob 已提交
991
				if ( geometryAttribute !== undefined ) {
M
Mr.doob 已提交
992

993
					var type = _gl.FLOAT;
994
					var array = geometryAttribute.array;
995 996
					var normalized = geometryAttribute.normalized;

997 998
					if ( array instanceof Float32Array ) {

999
						type = _gl.FLOAT;
1000 1001 1002 1003 1004 1005 1006

					} else if ( array instanceof Float64Array ) {

						console.warn("Unsupported data buffer format: Float64Array");

					} else if ( array instanceof Uint16Array ) {

1007 1008
						type = _gl.UNSIGNED_SHORT;

1009 1010
					} else if ( array instanceof Int16Array ) {

1011
						type = _gl.SHORT;
1012 1013 1014

					} else if ( array instanceof Uint32Array ) {

1015
						type = _gl.UNSIGNED_INT;
1016 1017 1018

					} else if ( array instanceof Int32Array ) {

1019
						type = _gl.INT;
1020 1021 1022

					} else if ( array instanceof Int8Array ) {

1023
						type = _gl.BYTE;
1024 1025 1026

					} else if ( array instanceof Uint8Array ) {

1027
						type = _gl.UNSIGNED_BYTE;
1028 1029

					}
1030

1031
					var size = geometryAttribute.itemSize;
G
gero3 已提交
1032
					var buffer = objects.getAttributeBuffer( geometryAttribute );
1033

B
Ben Adams 已提交
1034
					if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
1035

M
Mr.doob 已提交
1036 1037 1038 1039 1040
						var data = geometryAttribute.data;
						var stride = data.stride;
						var offset = geometryAttribute.offset;

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

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

M
Mr.doob 已提交
1044
							if ( geometry.maxInstancedCount === undefined ) {
1045

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

M
Mr.doob 已提交
1048
							}
B
Ben Adams 已提交
1049

M
Mr.doob 已提交
1050
						} else {
B
Ben Adams 已提交
1051

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

M
Mr.doob 已提交
1054
						}
B
Ben Adams 已提交
1055

M
Mr.doob 已提交
1056
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
1057
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
B
Ben Adams 已提交
1058

M
Mr.doob 已提交
1059
					} else {
B
Ben Adams 已提交
1060

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

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

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

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

M
Mr.doob 已提交
1069
							}
B
Ben Adams 已提交
1070

M
Mr.doob 已提交
1071 1072 1073 1074
						} else {

							state.enableAttribute( programAttribute );

M
Mr.doob 已提交
1075
						}
B
Ben Adams 已提交
1076

M
Mr.doob 已提交
1077
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
1078
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
M
Mr.doob 已提交
1079

B
Ben Adams 已提交
1080
					}
M
Mr.doob 已提交
1081

1082 1083
				} else if ( materialDefaultAttributeValues !== undefined ) {

T
tschw 已提交
1084
					var value = materialDefaultAttributeValues[ name ];
1085

1086
					if ( value !== undefined ) {
M
Mr.doob 已提交
1087

1088
						switch ( value.length ) {
M
Mr.doob 已提交
1089

1090 1091 1092
							case 2:
								_gl.vertexAttrib2fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1093

1094 1095 1096
							case 3:
								_gl.vertexAttrib3fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1097

1098 1099 1100
							case 4:
								_gl.vertexAttrib4fv( programAttribute, value );
								break;
1101

1102 1103
							default:
								_gl.vertexAttrib1fv( programAttribute, value );
1104 1105

						}
M
Mr.doob 已提交
1106 1107 1108 1109 1110 1111 1112 1113

					}

				}

			}

		}
1114

1115
		state.disableUnusedAttributes();
1116

M
Mr.doob 已提交
1117 1118
	}

M
Mr.doob 已提交
1119 1120
	// Sorting

1121
	function absNumericalSort( a, b ) {
1122

1123
		return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
1124 1125 1126

	}

M
Mr.doob 已提交
1127 1128
	function painterSortStable ( a, b ) {

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

U
unconed 已提交
1131
			return a.object.renderOrder - b.object.renderOrder;
1132

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

M
Mr.doob 已提交
1135
			return a.material.id - b.material.id;
1136 1137

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

M
Mr.doob 已提交
1139
			return a.z - b.z;
M
Mr.doob 已提交
1140 1141 1142

		} else {

1143
			return a.id - b.id;
M
Mr.doob 已提交
1144 1145 1146

		}

1147
	}
M
Mr.doob 已提交
1148

1149 1150
	function reversePainterSortStable ( a, b ) {

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

U
unconed 已提交
1153
			return a.object.renderOrder - b.object.renderOrder;
1154 1155

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

M
Mr.doob 已提交
1157
			return b.z - a.z;
1158 1159 1160 1161 1162 1163 1164

		} else {

			return a.id - b.id;

		}

1165
	}
1166

M
Mr.doob 已提交
1167 1168 1169 1170 1171 1172
	// Rendering

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

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

1173
			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
M
Mr.doob 已提交
1174 1175 1176 1177
			return;

		}

M
Mr.doob 已提交
1178
		var fog = scene.fog;
M
Mr.doob 已提交
1179 1180 1181

		// reset caching for this frame

1182
		_currentGeometryProgram = '';
1183
		_currentMaterialId = - 1;
1184
		_currentCamera = null;
M
Mr.doob 已提交
1185 1186 1187

		// update scene graph

1188
		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
M
Mr.doob 已提交
1189 1190 1191

		// update camera matrices and frustum

1192
		if ( camera.parent === null ) camera.updateMatrixWorld();
M
Mr.doob 已提交
1193 1194 1195 1196 1197 1198

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

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

M
Mr.doob 已提交
1199
		lights.length = 0;
1200

M
Mr.doob 已提交
1201 1202
		opaqueObjectsLastIndex = - 1;
		transparentObjectsLastIndex = - 1;
1203

M
Mr.doob 已提交
1204 1205 1206
		sprites.length = 0;
		lensFlares.length = 0;

T
tschw 已提交
1207 1208 1209
		_localClippingEnabled = this.localClippingEnabled;
		_clippingEnabled = _clipping.init(
				this.clippingPlanes, _localClippingEnabled, camera );
T
tschw 已提交
1210

1211
		projectObject( scene, camera );
M
Mr.doob 已提交
1212

T
tschw 已提交
1213

1214 1215 1216
		opaqueObjects.length = opaqueObjectsLastIndex + 1;
		transparentObjects.length = transparentObjectsLastIndex + 1;

M
Mr.doob 已提交
1217
		if ( _this.sortObjects === true ) {
1218 1219 1220

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

1222 1223
		}

M
Mr.doob 已提交
1224
		//
M
Mr.doob 已提交
1225

T
tschw 已提交
1226
		if ( _clippingEnabled ) _clipping.beginShadows();
T
tschw 已提交
1227

1228 1229
		setupShadows( lights );

M
Mr.doob 已提交
1230
		shadowMap.render( scene, camera );
M
Mr.doob 已提交
1231

1232 1233
		setupLights( lights, camera );

T
tschw 已提交
1234
		if ( _clippingEnabled ) _clipping.endShadows();
T
tschw 已提交
1235

M
Mr.doob 已提交
1236 1237
		//

1238 1239 1240 1241
		_infoRender.calls = 0;
		_infoRender.vertices = 0;
		_infoRender.faces = 0;
		_infoRender.points = 0;
M
Mr.doob 已提交
1242

1243 1244 1245 1246 1247 1248
		if ( renderTarget === undefined ) {

			renderTarget = null;

		}

M
Mr.doob 已提交
1249 1250 1251 1252 1253 1254 1255 1256
		this.setRenderTarget( renderTarget );

		if ( this.autoClear || forceClear ) {

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

		}

1257
		//
M
Mr.doob 已提交
1258 1259 1260

		if ( scene.overrideMaterial ) {

1261
			var overrideMaterial = scene.overrideMaterial;
M
Mr.doob 已提交
1262

1263 1264
			renderObjects( opaqueObjects, camera, fog, overrideMaterial );
			renderObjects( transparentObjects, camera, fog, overrideMaterial );
1265

M
Mr.doob 已提交
1266 1267 1268 1269
		} else {

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

M
Mr.doob 已提交
1270
			state.setBlending( THREE.NoBlending );
1271
			renderObjects( opaqueObjects, camera, fog );
M
Mr.doob 已提交
1272 1273 1274

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

1275
			renderObjects( transparentObjects, camera, fog );
M
Mr.doob 已提交
1276 1277 1278 1279 1280

		}

		// custom render plugins (post pass)

M
Mr.doob 已提交
1281
		spritePlugin.render( scene, camera );
1282
		lensFlarePlugin.render( scene, camera, _currentViewport );
M
Mr.doob 已提交
1283 1284 1285

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

M
Mr.doob 已提交
1286 1287 1288
		if ( renderTarget ) {

			var texture = renderTarget.texture;
M
Mr.doob 已提交
1289

M
Mr.doob 已提交
1290 1291 1292 1293 1294
			if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
					texture.minFilter !== THREE.NearestFilter &&
					texture.minFilter !== THREE.LinearFilter ) {

				updateRenderTargetMipmap( renderTarget );
M
Mr.doob 已提交
1295 1296

			}
M
Mr.doob 已提交
1297 1298 1299

		}

1300
		// Ensure depth buffer writing is enabled so it can be cleared on next render
M
Mr.doob 已提交
1301

M
Mr.doob 已提交
1302 1303
		state.setDepthTest( true );
		state.setDepthWrite( true );
1304
		state.setColorWrite( true );
M
Mr.doob 已提交
1305 1306 1307 1308

		// _gl.finish();

	};
M
Mr.doob 已提交
1309

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

1312
		var array, index;
M
Mr.doob 已提交
1313

1314
		// allocate the next position in the appropriate array
M
Mr.doob 已提交
1315 1316 1317

		if ( material.transparent ) {

1318 1319
			array = transparentObjects;
			index = ++ transparentObjectsLastIndex;
M
Mr.doob 已提交
1320 1321 1322

		} else {

1323 1324 1325 1326 1327
			array = opaqueObjects;
			index = ++ opaqueObjectsLastIndex;

		}

1328 1329
		// recycle existing render item or grow the array

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
		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 已提交
1340 1341 1342

		} else {

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
			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 已提交
1354 1355 1356 1357 1358

		}

	}

T
tschw 已提交
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
	function isObjectViewable( object ) {

		var geometry = object.geometry;

		if ( geometry.boundingSphere === null )
			geometry.computeBoundingSphere();

		var sphere = _sphere.
				copy( geometry.boundingSphere ).
				applyMatrix4( object.matrixWorld );

		if ( ! _frustum.intersectsSphere( sphere ) ) return false;
T
tschw 已提交
1371 1372 1373 1374

		var numPlanes = _clipping.numPlanes;

		if ( numPlanes === 0 ) return true;
T
tschw 已提交
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

		var planes = _this.clippingPlanes,

			center = sphere.center,
			negRad = - sphere.radius,
			i = 0;

		do {

			// out when deeper than radius in the negative halfspace
			if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;

T
tschw 已提交
1387
		} while ( ++ i !== numPlanes );
T
tschw 已提交
1388 1389 1390 1391 1392

		return true;

	}

1393
	function projectObject( object, camera ) {
M
Mr.doob 已提交
1394

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

1397
		if ( object.layers.test( camera.layers ) ) {
M
Mr.doob 已提交
1398

1399
			if ( object instanceof THREE.Light ) {
M
Mr.doob 已提交
1400

1401
				lights.push( object );
M
Mr.doob 已提交
1402

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

T
tschw 已提交
1405
				if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
1406 1407 1408 1409

					sprites.push( object );

				}
M
Mr.doob 已提交
1410

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

1413
				lensFlares.push( object );
M
Mr.doob 已提交
1414

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

1417
				if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1418

1419 1420
					_vector3.setFromMatrixPosition( object.matrixWorld );
					_vector3.applyProjection( _projScreenMatrix );
M
Mr.doob 已提交
1421

1422
				}
1423

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

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

1428
				if ( object instanceof THREE.SkinnedMesh ) {
M
Mr.doob 已提交
1429

1430
					object.skeleton.update();
1431

1432
				}
1433

T
tschw 已提交
1434
				if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
1435

1436
					var material = object.material;
1437

1438
					if ( material.visible === true ) {
M
Mr.doob 已提交
1439

1440
						if ( _this.sortObjects === true ) {
M
Mr.doob 已提交
1441

1442 1443 1444 1445
							_vector3.setFromMatrixPosition( object.matrixWorld );
							_vector3.applyProjection( _projScreenMatrix );

						}
M
Mr.doob 已提交
1446

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

S
SUNAG 已提交
1449
						if ( material instanceof THREE.MultiMaterial ) {
1450

1451 1452
							var groups = geometry.groups;
							var materials = material.materials;
1453

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

1456 1457
								var group = groups[ i ];
								var groupMaterial = materials[ group.materialIndex ];
1458

1459
								if ( groupMaterial.visible === true ) {
1460

1461 1462 1463
									pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );

								}
M
Mr.doob 已提交
1464

M
Mr.doob 已提交
1465
							}
M
Mr.doob 已提交
1466

1467
						} else {
M
Mr.doob 已提交
1468

1469
							pushRenderItem( object, geometry, material, _vector3.z, null );
1470

1471
						}
O
OpenShift guest 已提交
1472

1473
					}
M
Mr.doob 已提交
1474

1475
				}
M
Mr.doob 已提交
1476

1477
			}
M
Mr.doob 已提交
1478

M
Mr.doob 已提交
1479
		}
M
Mr.doob 已提交
1480

M
Mr.doob 已提交
1481
		var children = object.children;
M
Mr.doob 已提交
1482

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

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

1487
		}
1488

1489
	}
M
Mr.doob 已提交
1490

1491
	function renderObjects( renderList, camera, fog, overrideMaterial ) {
M
Mr.doob 已提交
1492

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

1495
			var renderItem = renderList[ i ];
M
Mr.doob 已提交
1496

1497
			var object = renderItem.object;
M
Mr.doob 已提交
1498 1499 1500
			var geometry = renderItem.geometry;
			var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
			var group = renderItem.group;
M
Mr.doob 已提交
1501

1502 1503
			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
M
Mr.doob 已提交
1504

M
Mr.doob 已提交
1505
			if ( object instanceof THREE.ImmediateRenderObject ) {
M
Mr.doob 已提交
1506

M
Mr.doob 已提交
1507
				setMaterial( material );
M
Mr.doob 已提交
1508

1509
				var program = setProgram( camera, fog, material, object );
M
Mr.doob 已提交
1510

M
Mr.doob 已提交
1511
				_currentGeometryProgram = '';
M
Mr.doob 已提交
1512

M
Mr.doob 已提交
1513
				object.render( function ( object ) {
M
Mr.doob 已提交
1514

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

M
Mr.doob 已提交
1517
				} );
1518

M
Mr.doob 已提交
1519
			} else {
M
Mr.doob 已提交
1520

1521
				_this.renderBufferDirect( camera, fog, geometry, material, object, group );
M
Mr.doob 已提交
1522

M
Mr.doob 已提交
1523
			}
M
Mr.doob 已提交
1524

1525
		}
M
Mr.doob 已提交
1526

1527
	}
G
gero3 已提交
1528

1529
	function initMaterial( material, fog, object ) {
M
Mr.doob 已提交
1530

1531
		var materialProperties = properties.get( material );
G
gero3 已提交
1532

T
tschw 已提交
1533
		var parameters = programCache.getParameters(
T
tschw 已提交
1534
				material, _lights, fog, _clipping.numPlanes, object );
T
tschw 已提交
1535

G
gero3 已提交
1536
		var code = programCache.getProgramCode( material, parameters );
G
gero3 已提交
1537

1538
		var program = materialProperties.program;
T
tschw 已提交
1539
		var programChange = true;
1540

1541
		if ( program === undefined ) {
B
Ben Adams 已提交
1542

M
Mr.doob 已提交
1543 1544
			// new material
			material.addEventListener( 'dispose', onMaterialDispose );
B
Ben Adams 已提交
1545

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

M
Mr.doob 已提交
1548
			// changed glsl or parameters
1549
			releaseMaterialProgramReference( material );
B
Ben Adams 已提交
1550

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

T
tschw 已提交
1553
			// same glsl and uniform list
T
tschw 已提交
1554 1555
			return;

T
tschw 已提交
1556
		} else {
B
Ben Adams 已提交
1557

T
tschw 已提交
1558 1559
			// only rebuild uniform list
			programChange = false;
B
Ben Adams 已提交
1560 1561 1562

		}

1563
		if ( programChange ) {
B
Ben Adams 已提交
1564

1565
			if ( parameters.shaderID ) {
B
Ben Adams 已提交
1566

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

1569 1570 1571 1572 1573 1574
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};
B
Ben Adams 已提交
1575

1576
			} else {
B
Ben Adams 已提交
1577

1578 1579 1580 1581 1582 1583
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};
G
gero3 已提交
1584

1585
			}
G
gero3 已提交
1586

1587
			material.__webglShader = materialProperties.__webglShader;
G
gero3 已提交
1588

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

1591 1592
			materialProperties.program = program;
			material.program = program;
1593 1594 1595

		}

1596
		var attributes = program.getAttributes();
M
Mr.doob 已提交
1597 1598 1599 1600 1601

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

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

M
Mr.doob 已提交
1604
				if ( attributes[ 'morphTarget' + i ] >= 0 ) {
M
Mr.doob 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

M
Mr.doob 已提交
1618
			for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
M
Mr.doob 已提交
1619

M
Mr.doob 已提交
1620
				if ( attributes[ 'morphNormal' + i ] >= 0 ) {
M
Mr.doob 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629

					material.numSupportedMorphNormals ++;

				}

			}

		}

T
tschw 已提交
1630 1631 1632 1633 1634 1635
		var uniforms = materialProperties.__webglShader.uniforms;

		if ( ! ( material instanceof THREE.ShaderMaterial ) &&
				! ( material instanceof THREE.RawShaderMaterial ) ||
				material.clipping === true ) {

T
tschw 已提交
1636 1637
			materialProperties.numClippingPlanes = _clipping.numPlanes;
			uniforms.clippingPlanes = _clipping.uniform;
T
tschw 已提交
1638 1639 1640

		}

M
Mr.doob 已提交
1641
		if ( material.lights ) {
1642

1643 1644
			// store the light setup it was created for

1645 1646
			materialProperties.lightsHash = _lights.hash;

1647 1648 1649 1650 1651
			// wire up the material to this renderer's lighting state

			uniforms.ambientLightColor.value = _lights.ambient;
			uniforms.directionalLights.value = _lights.directional;
			uniforms.spotLights.value = _lights.spot;
M
Mr.doob 已提交
1652
			uniforms.pointLights.value = _lights.point;
1653 1654
			uniforms.hemisphereLights.value = _lights.hemi;

1655 1656 1657 1658 1659 1660
			uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
			uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
			uniforms.spotShadowMap.value = _lights.spotShadowMap;
			uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
			uniforms.pointShadowMap.value = _lights.pointShadowMap;
			uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
1661

1662 1663
		}

T
tschw 已提交
1664 1665 1666
		var progUniforms = materialProperties.program.getUniforms(),
			uniformsList =
					THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
A
arose 已提交
1667

T
tschw 已提交
1668 1669 1670
		materialProperties.uniformsList = uniformsList;
		materialProperties.dynamicUniforms =
				THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms );
A
arose 已提交
1671

M
Mr.doob 已提交
1672
	}
M
Mr.doob 已提交
1673

1674 1675
	function setMaterial( material ) {

T
tschw 已提交
1676 1677 1678 1679 1680 1681
		if ( material.side !== THREE.DoubleSide )
			state.enable( _gl.CULL_FACE );
		else
			state.disable( _gl.CULL_FACE );

		state.setFlipSided( material.side === THREE.BackSide );
M
Mr.doob 已提交
1682

1683 1684
		if ( material.transparent === true ) {

1685
			state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
1686

1687 1688 1689 1690
		} else {

			state.setBlending( THREE.NoBlending );

1691 1692
		}

B
Ben Adams 已提交
1693
		state.setDepthFunc( material.depthFunc );
M
Mr.doob 已提交
1694 1695
		state.setDepthTest( material.depthTest );
		state.setDepthWrite( material.depthWrite );
1696
		state.setColorWrite( material.colorWrite );
M
Mr.doob 已提交
1697
		state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
1698 1699 1700

	}

1701
	function setProgram( camera, fog, material, object ) {
M
Mr.doob 已提交
1702 1703 1704

		_usedTextureUnits = 0;

1705
		var materialProperties = properties.get( material );
1706

T
tschw 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
		if ( _clippingEnabled ) {

			if ( _localClippingEnabled || camera !== _currentCamera ) {

				var useCache =
						camera === _currentCamera &&
						material.id === _currentMaterialId;

				// we might want to call this function with some ClippingGroup
				// object instead of the material, once it becomes feasible
				// (#8465, #8379)
T
tschw 已提交
1718
				_clipping.setState(
T
tschw 已提交
1719 1720 1721 1722 1723 1724
						material.clippingPlanes, material.clipShadows,
						camera, materialProperties, useCache );

			}

			if ( materialProperties.numClippingPlanes !== undefined &&
T
tschw 已提交
1725
				materialProperties.numClippingPlanes !== _clipping.numPlanes ) {
T
tschw 已提交
1726 1727 1728 1729 1730 1731 1732

				material.needsUpdate = true;

			}

		}

1733 1734 1735 1736 1737 1738
		if ( materialProperties.program === undefined ) {

			material.needsUpdate = true;

		}

1739 1740
		if ( materialProperties.lightsHash !== undefined &&
			materialProperties.lightsHash !== _lights.hash ) {
1741 1742 1743 1744 1745 1746

			material.needsUpdate = true;

		}

		if ( material.needsUpdate ) {
M
Mr.doob 已提交
1747

1748
			initMaterial( material, fog, object );
M
Mr.doob 已提交
1749 1750 1751 1752
			material.needsUpdate = false;

		}

1753
		var refreshProgram = false;
M
Mr.doob 已提交
1754
		var refreshMaterial = false;
1755
		var refreshLights = false;
M
Mr.doob 已提交
1756

1757
		var program = materialProperties.program,
1758
			p_uniforms = program.getUniforms(),
1759
			m_uniforms = materialProperties.__webglShader.uniforms;
M
Mr.doob 已提交
1760

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

1763 1764
			_gl.useProgram( program.program );
			_currentProgram = program.id;
M
Mr.doob 已提交
1765

1766
			refreshProgram = true;
M
Mr.doob 已提交
1767
			refreshMaterial = true;
1768
			refreshLights = true;
M
Mr.doob 已提交
1769 1770 1771 1772 1773 1774

		}

		if ( material.id !== _currentMaterialId ) {

			_currentMaterialId = material.id;
1775

M
Mr.doob 已提交
1776 1777 1778 1779
			refreshMaterial = true;

		}

1780
		if ( refreshProgram || camera !== _currentCamera ) {
M
Mr.doob 已提交
1781

T
tschw 已提交
1782
			p_uniforms.set( _gl, camera, 'projectionMatrix' );
M
Mr.doob 已提交
1783

G
gero3 已提交
1784
			if ( capabilities.logarithmicDepthBuffer ) {
1785

T
tschw 已提交
1786 1787
				p_uniforms.setValue( _gl, 'logDepthBufFC',
						2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
1788 1789 1790 1791

			}


1792 1793 1794 1795 1796 1797 1798 1799 1800
			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
T
tschw 已提交
1801
				refreshLights = true;		// remains set until update done
1802 1803

			}
M
Mr.doob 已提交
1804

1805 1806 1807 1808 1809
			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

			if ( material instanceof THREE.ShaderMaterial ||
				 material instanceof THREE.MeshPhongMaterial ||
1810
				 material instanceof THREE.MeshStandardMaterial ||
1811 1812
				 material.envMap ) {

T
tschw 已提交
1813 1814 1815
				var uCamPos = p_uniforms.map.cameraPosition;

				if ( uCamPos !== undefined ) {
1816

T
tschw 已提交
1817 1818
					uCamPos.setValue( _gl,
							_vector3.setFromMatrixPosition( camera.matrixWorld ) );
1819 1820 1821 1822 1823 1824 1825

				}

			}

			if ( material instanceof THREE.MeshPhongMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
1826
				 material instanceof THREE.MeshBasicMaterial ||
1827
				 material instanceof THREE.MeshStandardMaterial ||
1828 1829 1830
				 material instanceof THREE.ShaderMaterial ||
				 material.skinning ) {

T
tschw 已提交
1831
				p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
1832 1833 1834

			}

T
tschw 已提交
1835 1836
			p_uniforms.set( _gl, _this, 'toneMappingExposure' );
			p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
M
Mr.doob 已提交
1837

M
Mr.doob 已提交
1838 1839 1840 1841 1842 1843 1844 1845
		}

		// 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 ) {

T
tschw 已提交
1846 1847
			p_uniforms.setOptional( _gl, object, 'bindMatrix' );
			p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
1848

T
tschw 已提交
1849
			var skeleton = object.skeleton;
1850

T
tschw 已提交
1851
			if ( skeleton ) {
1852

T
tschw 已提交
1853
				if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
M
Mr.doob 已提交
1854

T
tschw 已提交
1855 1856 1857
					p_uniforms.set( _gl, skeleton, 'boneTexture' );
					p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
					p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
M
Mr.doob 已提交
1858

T
tschw 已提交
1859
				} else {
M
Mr.doob 已提交
1860

T
tschw 已提交
1861
					p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
M
Mr.doob 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870

				}

			}

		}

		if ( refreshMaterial ) {

M
Mr.doob 已提交
1871
			if ( material.lights ) {
M
Mr.doob 已提交
1872

1873
				// the current material requires lighting info
M
Mr.doob 已提交
1874

T
tschw 已提交
1875 1876 1877 1878 1879 1880
				// note: all lighting uniforms are always set correctly
				// they simply reference the renderer's state for their
				// values
				//
				// use the current material's .needsUpdate flags to set
				// the GL state when required
M
Mr.doob 已提交
1881

T
tschw 已提交
1882
				markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
G
gero3 已提交
1883

T
tschw 已提交
1884
			}
G
gero3 已提交
1885

T
tschw 已提交
1886
			// refresh uniforms common to several materials
G
gero3 已提交
1887

T
tschw 已提交
1888
			if ( fog && material.fog ) {
G
gero3 已提交
1889

T
tschw 已提交
1890
				refreshUniformsFog( m_uniforms, fog );
M
Mr.doob 已提交
1891 1892 1893 1894 1895

			}

			if ( material instanceof THREE.MeshBasicMaterial ||
				 material instanceof THREE.MeshLambertMaterial ||
W
WestLangley 已提交
1896
				 material instanceof THREE.MeshPhongMaterial ||
W
WestLangley 已提交
1897 1898
				 material instanceof THREE.MeshStandardMaterial ||
				 material instanceof THREE.MeshDepthMaterial ) {
M
Mr.doob 已提交
1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914

				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 );

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

M
Mr.doob 已提交
1917
				refreshUniformsPoints( m_uniforms, material );
M
Mr.doob 已提交
1918

1919 1920 1921 1922
			} else if ( material instanceof THREE.MeshLambertMaterial ) {

				refreshUniformsLambert( m_uniforms, material );

M
Mr.doob 已提交
1923 1924 1925 1926
			} else if ( material instanceof THREE.MeshPhongMaterial ) {

				refreshUniformsPhong( m_uniforms, material );

W
WestLangley 已提交
1927 1928 1929 1930
			} else if ( material instanceof THREE.MeshPhysicalMaterial ) {

				refreshUniformsPhysical( m_uniforms, material );

1931
			} else if ( material instanceof THREE.MeshStandardMaterial ) {
W
WestLangley 已提交
1932

1933
				refreshUniformsStandard( m_uniforms, material );
W
WestLangley 已提交
1934

M
Mr.doob 已提交
1935 1936
			} else if ( material instanceof THREE.MeshDepthMaterial ) {

1937 1938 1939 1940 1941 1942 1943 1944
				if ( material.displacementMap ) {

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

				}

M
Mr.doob 已提交
1945 1946 1947 1948 1949 1950
			} else if ( material instanceof THREE.MeshNormalMaterial ) {

				m_uniforms.opacity.value = material.opacity;

			}

T
tschw 已提交
1951 1952
			THREE.WebGLUniforms.upload(
					_gl, materialProperties.uniformsList, m_uniforms, _this );
A
arose 已提交
1953 1954 1955

		}

M
Mr.doob 已提交
1956

T
tschw 已提交
1957
		// common matrices
M
Mr.doob 已提交
1958

T
tschw 已提交
1959 1960 1961
		p_uniforms.set( _gl, object, 'modelViewMatrix' );
		p_uniforms.set( _gl, object, 'normalMatrix' );
		p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
A
arose 已提交
1962 1963


T
tschw 已提交
1964
		// dynamic uniforms
A
arose 已提交
1965

T
tschw 已提交
1966
		var dynUniforms = materialProperties.dynamicUniforms;
A
arose 已提交
1967

T
tschw 已提交
1968
		if ( dynUniforms !== null ) {
A
arose 已提交
1969

T
tschw 已提交
1970 1971
			THREE.WebGLUniforms.evalDynamic(
					dynUniforms, m_uniforms, object, camera );
A
arose 已提交
1972

T
tschw 已提交
1973
			THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
A
arose 已提交
1974 1975 1976

		}

T
tschw 已提交
1977
		return program;
A
arose 已提交
1978 1979 1980

	}

M
Mr.doob 已提交
1981 1982 1983 1984 1985 1986
	// Uniforms (refresh uniforms objects)

	function refreshUniformsCommon ( uniforms, material ) {

		uniforms.opacity.value = material.opacity;

1987
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
1988

1989
		if ( material.emissive ) {
M
Mr.doob 已提交
1990

1991
			uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
M
Mr.doob 已提交
1992 1993 1994

		}

1995 1996 1997
		uniforms.map.value = material.map;
		uniforms.specularMap.value = material.specularMap;
		uniforms.alphaMap.value = material.alphaMap;
M
Mr.doob 已提交
1998

1999
		if ( material.aoMap ) {
2000

2001 2002
			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;
2003 2004 2005

		}

M
Mr.doob 已提交
2006
		// uv repeat and offset setting priorities
M
Mr.doob 已提交
2007 2008 2009 2010 2011
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
2012
		// 6. emissive map
M
Mr.doob 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023

		var uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

2024 2025 2026 2027
		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

M
Mr.doob 已提交
2028 2029 2030 2031 2032 2033 2034 2035
		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

2036 2037 2038 2039 2040 2041 2042 2043
		} else if ( material.roughnessMap ) {

			uvScaleMap = material.roughnessMap;

		} else if ( material.metalnessMap ) {

			uvScaleMap = material.metalnessMap;

2044 2045 2046 2047
		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

2048 2049 2050 2051
		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

M
Mr.doob 已提交
2052 2053 2054 2055
		}

		if ( uvScaleMap !== undefined ) {

2056
			// backwards compatibility
M
Mr.doob 已提交
2057 2058 2059 2060 2061 2062
			if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {

				uvScaleMap = uvScaleMap.texture;

			}

M
Mr.doob 已提交
2063 2064 2065 2066 2067 2068 2069 2070
			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;
2071 2072 2073 2074 2075 2076

		// don't flip CubeTexture envMaps, flip everything else:
		//  WebGLRenderTargetCube will be flipped for backwards compatibility
		//  WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
		// this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
		uniforms.flipEnvMap.value = ( ! ( material.envMap instanceof THREE.CubeTexture ) ) ? 1 : - 1;
M
Mr.doob 已提交
2077

2078
		uniforms.reflectivity.value = material.reflectivity;
M
Mr.doob 已提交
2079 2080
		uniforms.refractionRatio.value = material.refractionRatio;

M
Mr.doob 已提交
2081
	}
M
Mr.doob 已提交
2082 2083 2084 2085 2086 2087

	function refreshUniformsLine ( uniforms, material ) {

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

M
Mr.doob 已提交
2088
	}
M
Mr.doob 已提交
2089 2090 2091 2092 2093 2094 2095

	function refreshUniformsDash ( uniforms, material ) {

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

M
Mr.doob 已提交
2096
	}
M
Mr.doob 已提交
2097

M
Mr.doob 已提交
2098
	function refreshUniformsPoints ( uniforms, material ) {
M
Mr.doob 已提交
2099

2100
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
2101
		uniforms.opacity.value = material.opacity;
2102
		uniforms.size.value = material.size * _pixelRatio;
T
tschw 已提交
2103
		uniforms.scale.value = _canvas.clientHeight * 0.5;
M
Mr.doob 已提交
2104 2105 2106

		uniforms.map.value = material.map;

2107 2108 2109 2110 2111 2112 2113 2114 2115
		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 已提交
2116
	}
M
Mr.doob 已提交
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132

	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 已提交
2133
	}
M
Mr.doob 已提交
2134

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
	function refreshUniformsLambert ( uniforms, material ) {

		if ( material.lightMap ) {

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

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

	}

M
Mr.doob 已提交
2152 2153
	function refreshUniformsPhong ( uniforms, material ) {

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

2157 2158 2159 2160
		if ( material.lightMap ) {

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

2162
		}
2163

2164
		if ( material.emissiveMap ) {
2165

2166
			uniforms.emissiveMap.value = material.emissiveMap;
2167

2168
		}
M
Mr.doob 已提交
2169

2170 2171 2172 2173
		if ( material.bumpMap ) {

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

2175
		}
M
Mr.doob 已提交
2176

2177 2178 2179 2180 2181 2182
		if ( material.normalMap ) {

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

		}
M
Mr.doob 已提交
2183

2184 2185 2186 2187 2188
		if ( material.displacementMap ) {

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

2190
		}
2191 2192 2193

	}

2194
	function refreshUniformsStandard ( uniforms, material ) {
W
WestLangley 已提交
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254

		uniforms.roughness.value = material.roughness;
		uniforms.metalness.value = material.metalness;

		if ( material.roughnessMap ) {

			uniforms.roughnessMap.value = material.roughnessMap;

		}

		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;

		}

	}

W
WestLangley 已提交
2255 2256 2257 2258 2259 2260
	function refreshUniformsPhysical ( uniforms, material ) {

		refreshUniformsStandard( uniforms, material );

	}

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

M
Mr.doob 已提交
2263
	function markUniformsLightsNeedsUpdate ( uniforms, value ) {
2264

M
Mr.doob 已提交
2265
		uniforms.ambientLightColor.needsUpdate = value;
2266

B
Ben Houston 已提交
2267 2268 2269 2270
		uniforms.directionalLights.needsUpdate = value;
		uniforms.pointLights.needsUpdate = value;
		uniforms.spotLights.needsUpdate = value;
		uniforms.hemisphereLights.needsUpdate = value;
2271

M
Mr.doob 已提交
2272
	}
2273

T
tschw 已提交
2274
	// Lighting
M
Mr.doob 已提交
2275

2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
	function setupShadows ( lights ) {

		var lightShadowsLength = 0;

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

			var light = lights[ i ];

			if ( light.castShadow ) {

				_lights.shadows[ lightShadowsLength ++ ] = light;

			}

		}

		_lights.shadows.length = lightShadowsLength;

	}

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

B
brason 已提交
2298
		var l, ll, light,
M
Mr.doob 已提交
2299
		r = 0, g = 0, b = 0,
B
Ben Houston 已提交
2300
		color,
B
brason 已提交
2301
		intensity,
M
Mr.doob 已提交
2302
		distance,
2303
		shadowMap,
M
Mr.doob 已提交
2304

2305
		viewMatrix = camera.matrixWorldInverse,
M
Mr.doob 已提交
2306

M
Mr.doob 已提交
2307
		directionalLength = 0,
M
Mr.doob 已提交
2308 2309
		pointLength = 0,
		spotLength = 0,
2310
		hemiLength = 0;
M
Mr.doob 已提交
2311 2312 2313 2314 2315 2316 2317 2318 2319

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

			light = lights[ l ];

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

2320 2321
			shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;

M
Mr.doob 已提交
2322 2323
			if ( light instanceof THREE.AmbientLight ) {

2324 2325 2326
				r += color.r * intensity;
				g += color.g * intensity;
				b += color.b * intensity;
M
Mr.doob 已提交
2327 2328 2329

			} else if ( light instanceof THREE.DirectionalLight ) {

M
Mr.doob 已提交
2330
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2331

2332
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
M
Mr.doob 已提交
2333
				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
2334
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
M
Mr.doob 已提交
2335 2336 2337
				uniforms.direction.sub( _vector3 );
				uniforms.direction.transformDirection( viewMatrix );

2338
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2339

2340
				if ( light.castShadow ) {
M
Mr.doob 已提交
2341

2342 2343 2344
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2345

2346 2347
				}

2348
				_lights.directionalShadowMap[ directionalLength ] = shadowMap;
2349
				_lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
2350
				_lights.directional[ directionalLength ++ ] = uniforms;
M
Mr.doob 已提交
2351

M
Mr.doob 已提交
2352
			} else if ( light instanceof THREE.SpotLight ) {
M
Mr.doob 已提交
2353

M
Mr.doob 已提交
2354
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2355 2356 2357

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2358

M
Mr.doob 已提交
2359 2360 2361 2362 2363 2364 2365 2366
				uniforms.color.copy( color ).multiplyScalar( intensity );
				uniforms.distance = distance;

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
				uniforms.direction.sub( _vector3 );
				uniforms.direction.transformDirection( viewMatrix );

2367 2368
				uniforms.coneCos = Math.cos( light.angle );
				uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
M
Mr.doob 已提交
2369
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2370

2371
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2372

2373 2374
				if ( light.castShadow ) {

2375 2376 2377
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2378

2379 2380
				}

2381
				_lights.spotShadowMap[ spotLength ] = shadowMap;
2382
				_lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
M
Mr.doob 已提交
2383
				_lights.spot[ spotLength ++ ] = uniforms;
2384

M
Mr.doob 已提交
2385
			} else if ( light instanceof THREE.PointLight ) {
M
Mr.doob 已提交
2386

M
Mr.doob 已提交
2387
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2388

M
Mr.doob 已提交
2389 2390
				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );
M
Mr.doob 已提交
2391

M
Mr.doob 已提交
2392 2393
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				uniforms.distance = light.distance;
M
Mr.doob 已提交
2394 2395
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;

2396
				uniforms.shadow = light.castShadow;
2397

M
Mr.doob 已提交
2398
				if ( light.castShadow ) {
2399

2400 2401 2402 2403 2404
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;

				}
2405

2406
				_lights.pointShadowMap[ pointLength ] = shadowMap;
2407

2408 2409 2410
				if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {

					_lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
2411

2412 2413
				}

2414 2415 2416 2417 2418
				// 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();
				_lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );

M
Mr.doob 已提交
2419
				_lights.point[ pointLength ++ ] = uniforms;
2420

M
Mr.doob 已提交
2421 2422
			} else if ( light instanceof THREE.HemisphereLight ) {

M
Mr.doob 已提交
2423
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2424 2425 2426 2427

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				uniforms.direction.transformDirection( viewMatrix );
				uniforms.direction.normalize();
M
Mr.doob 已提交
2428

M
Mr.doob 已提交
2429 2430
				uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
				uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
M
Mr.doob 已提交
2431

M
Mr.doob 已提交
2432
				_lights.hemi[ hemiLength ++ ] = uniforms;
M
Mr.doob 已提交
2433 2434 2435 2436 2437

			}

		}

M
Mr.doob 已提交
2438 2439 2440
		_lights.ambient[ 0 ] = r;
		_lights.ambient[ 1 ] = g;
		_lights.ambient[ 2 ] = b;
M
Mr.doob 已提交
2441

M
Mr.doob 已提交
2442 2443
		_lights.directional.length = directionalLength;
		_lights.spot.length = spotLength;
2444
		_lights.point.length = pointLength;
M
Mr.doob 已提交
2445
		_lights.hemi.length = hemiLength;
2446

2447
		_lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
2448

M
Mr.doob 已提交
2449
	}
M
Mr.doob 已提交
2450 2451 2452 2453 2454

	// GL state setting

	this.setFaceCulling = function ( cullFace, frontFaceDirection ) {

T
tschw 已提交
2455 2456
		state.setCullFace( cullFace );
		state.setFlipSided( frontFaceDirection === THREE.FrontFaceDirectionCW );
M
Mr.doob 已提交
2457 2458 2459 2460 2461

	};

	// Textures

T
tschw 已提交
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
	function allocTextureUnit() {

		var textureUnit = _usedTextureUnits;

		if ( textureUnit >= capabilities.maxTextures ) {

			console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );

		}

		_usedTextureUnits += 1;

		return textureUnit;

	}

M
Mr.doob 已提交
2478
	function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
M
Mr.doob 已提交
2479

2480 2481
		var extension;

M
Mr.doob 已提交
2482
		if ( isPowerOfTwoImage ) {
M
Mr.doob 已提交
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493

			_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 已提交
2494 2495 2496

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

M
Mr.doob 已提交
2497
				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 已提交
2498

2499
			}
M
Mr.doob 已提交
2500 2501 2502 2503

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

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

M
Mr.doob 已提交
2506
				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 已提交
2507

2508
			}
M
Mr.doob 已提交
2509

M
Mr.doob 已提交
2510 2511
		}

2512 2513
		extension = extensions.get( 'EXT_texture_filter_anisotropic' );

2514
		if ( extension ) {
M
Mr.doob 已提交
2515

2516 2517
			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 已提交
2518

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

2521
				_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
2522
				properties.get( texture ).__currentAnisotropy = texture.anisotropy;
M
Mr.doob 已提交
2523 2524 2525 2526 2527

			}

		}

M
Mr.doob 已提交
2528
	}
M
Mr.doob 已提交
2529

2530
	function uploadTexture( textureProperties, texture, slot ) {
2531

2532
		if ( textureProperties.__webglInit === undefined ) {
2533

2534
			textureProperties.__webglInit = true;
2535 2536 2537

			texture.addEventListener( 'dispose', onTextureDispose );

2538
			textureProperties.__webglTexture = _gl.createTexture();
2539

2540
			_infoMemory.textures ++;
2541 2542

		}
M
Mr.doob 已提交
2543

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

H
Henri Astre 已提交
2547 2548 2549 2550
		_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 );

2551
		var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
2552

2553
		if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
M
Mr.doob 已提交
2554

2555
			image = makePowerOfTwo( image );
M
Mr.doob 已提交
2556 2557 2558

		}

M
Mr.doob 已提交
2559
		var isPowerOfTwoImage = isPowerOfTwo( image ),
H
Henri Astre 已提交
2560 2561
		glFormat = paramThreeToGL( texture.format ),
		glType = paramThreeToGL( texture.type );
M
Mr.doob 已提交
2562

M
Mr.doob 已提交
2563
		setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
M
Mr.doob 已提交
2564

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

2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
		if ( texture instanceof THREE.DepthTexture ) {

			// populate depth texture with dummy data

			var internalFormat = _gl.DEPTH_COMPONENT;

			if ( texture.type === THREE.FloatType ) {

				if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
				internalFormat = _gl.DEPTH_COMPONENT32F;

			} else if ( _isWebGL2 ) {

				// WebGL 2.0 requires signed internalformat for glTexImage2D
				internalFormat = _gl.DEPTH_COMPONENT16;

			}

			state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );

		} else if ( texture instanceof THREE.DataTexture ) {
M
Mr.doob 已提交
2588

H
Henri Astre 已提交
2589 2590 2591
			// 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 已提交
2592

M
Mr.doob 已提交
2593
			if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
H
Henri Astre 已提交
2594 2595

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

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

H
Henri Astre 已提交
2600
				}
M
Mr.doob 已提交
2601

H
Henri Astre 已提交
2602
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2603

H
Henri Astre 已提交
2604
			} else {
M
Mr.doob 已提交
2605

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

H
Henri Astre 已提交
2608
			}
M
Mr.doob 已提交
2609

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

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

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

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

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

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

2622
					} else {
M
Mr.doob 已提交
2623

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

2626
					}
M
Mr.doob 已提交
2627

H
Henri Astre 已提交
2628
				} else {
M
Mr.doob 已提交
2629

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

M
Mr.doob 已提交
2632 2633
				}

H
Henri Astre 已提交
2634 2635
			}

G
gero3 已提交
2636 2637 2638
		} else {

			// regular Texture (image, video, canvas)
H
Henri Astre 已提交
2639 2640 2641 2642 2643

			// 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 已提交
2644
			if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
M
Mr.doob 已提交
2645

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

					mipmap = mipmaps[ i ];
2649
					state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
M
Mr.doob 已提交
2650 2651 2652

				}

H
Henri Astre 已提交
2653
				texture.generateMipmaps = false;
M
Mr.doob 已提交
2654

H
Henri Astre 已提交
2655
			} else {
M
Mr.doob 已提交
2656

2657
				state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
M
Mr.doob 已提交
2658

H
Henri Astre 已提交
2659
			}
M
Mr.doob 已提交
2660

H
Henri Astre 已提交
2661
		}
M
Mr.doob 已提交
2662

M
Mr.doob 已提交
2663
		if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
M
Mr.doob 已提交
2664

2665
		textureProperties.__version = texture.version;
M
Mr.doob 已提交
2666

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

2669
	}
M
Mr.doob 已提交
2670

T
tschw 已提交
2671 2672
	function setTexture2D( texture, slot ) {

2673 2674 2675
		var textureProperties = properties.get( texture );

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

2677
			var image = texture.image;
M
Mr.doob 已提交
2678

2679 2680
			if ( image === undefined ) {

2681
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
2682 2683 2684 2685
				return;

			}

2686
			if ( image.complete === false ) {
M
Mr.doob 已提交
2687

2688
				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
2689 2690 2691 2692
				return;

			}

2693
			uploadTexture( textureProperties, texture, slot );
2694

2695
			return;
M
Mr.doob 已提交
2696 2697 2698

		}

B
Ben Adams 已提交
2699
		state.activeTexture( _gl.TEXTURE0 + slot );
2700
		state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
2701

M
Michael Herzog 已提交
2702
	}
M
Mr.doob 已提交
2703 2704 2705

	function clampToMaxSize ( image, maxSize ) {

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

2708 2709
			// Warning: Scaling through the canvas will only work with images that use
			// premultiplied alpha.
M
Mr.doob 已提交
2710

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

2713 2714 2715
			var canvas = document.createElement( 'canvas' );
			canvas.width = Math.floor( image.width * scale );
			canvas.height = Math.floor( image.height * scale );
M
Mr.doob 已提交
2716

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

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

2722 2723 2724
			return canvas;

		}
M
Mr.doob 已提交
2725

2726
		return image;
M
Mr.doob 已提交
2727 2728 2729

	}

M
Mr.doob 已提交
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
	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;

	}

2766
	function setTextureCube ( texture, slot ) {
M
Mr.doob 已提交
2767

2768
		var textureProperties = properties.get( texture );
2769

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

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

2774
				if ( ! textureProperties.__image__webglTextureCube ) {
M
Mr.doob 已提交
2775

2776 2777
					texture.addEventListener( 'dispose', onTextureDispose );

2778
					textureProperties.__image__webglTextureCube = _gl.createTexture();
M
Mr.doob 已提交
2779

2780
					_infoMemory.textures ++;
M
Mr.doob 已提交
2781 2782 2783

				}

B
Ben Adams 已提交
2784
				state.activeTexture( _gl.TEXTURE0 + slot );
2785
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
2786 2787 2788

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

M
Mr.doob 已提交
2789 2790
				var isCompressed = texture instanceof THREE.CompressedTexture;
				var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
M
Mr.doob 已提交
2791 2792 2793 2794 2795

				var cubeImage = [];

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

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

G
gero3 已提交
2798
						cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
M
Mr.doob 已提交
2799 2800 2801

					} else {

2802
						cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
M
Mr.doob 已提交
2803 2804 2805 2806 2807 2808

					}

				}

				var image = cubeImage[ 0 ],
M
Mr.doob 已提交
2809
				isPowerOfTwoImage = isPowerOfTwo( image ),
M
Mr.doob 已提交
2810 2811 2812
				glFormat = paramThreeToGL( texture.format ),
				glType = paramThreeToGL( texture.type );

M
Mr.doob 已提交
2813
				setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
M
Mr.doob 已提交
2814 2815 2816

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

2817
					if ( ! isCompressed ) {
M
Mr.doob 已提交
2818

M
Mr.doob 已提交
2819
						if ( isDataTexture ) {
2820

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

M
Mr.doob 已提交
2823
						} else {
2824

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

M
Mr.doob 已提交
2827 2828
						}

2829
					} else {
2830

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

2833
						for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
M
Mr.doob 已提交
2834 2835

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

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

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

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

2843
								} else {
M
Mr.doob 已提交
2844

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

2847
								}
M
Mr.doob 已提交
2848

2849
							} else {
M
Mr.doob 已提交
2850

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

2853
							}
M
Mr.doob 已提交
2854

2855
						}
M
Mr.doob 已提交
2856

M
Mr.doob 已提交
2857
					}
M
Mr.doob 已提交
2858

M
Mr.doob 已提交
2859 2860
				}

M
Mr.doob 已提交
2861
				if ( texture.generateMipmaps && isPowerOfTwoImage ) {
M
Mr.doob 已提交
2862 2863 2864 2865 2866

					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

				}

2867
				textureProperties.__version = texture.version;
M
Mr.doob 已提交
2868

B
Ben Adams 已提交
2869
				if ( texture.onUpdate ) texture.onUpdate( texture );
M
Mr.doob 已提交
2870 2871 2872

			} else {

B
Ben Adams 已提交
2873
				state.activeTexture( _gl.TEXTURE0 + slot );
2874
				state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
M
Mr.doob 已提交
2875 2876 2877 2878 2879

			}

		}

M
Mr.doob 已提交
2880
	}
M
Mr.doob 已提交
2881

2882
	function setTextureCubeDynamic ( texture, slot ) {
M
Mr.doob 已提交
2883

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

M
Mr.doob 已提交
2887
	}
M
Mr.doob 已提交
2888

2889
	this.allocTextureUnit = allocTextureUnit;
T
tschw 已提交
2890

2891 2892
	//this.setTexture2D = setTexture2D;
	this.setTexture2D = ( function() {
T
tschw 已提交
2893

2894
		var warned = false;
T
tschw 已提交
2895

2896 2897
		// backwards compatibility: peel texture.texture
		return function( texture, slot ) {
T
tschw 已提交
2898

2899
			if ( texture instanceof THREE.WebGLRenderTarget ) {
T
tschw 已提交
2900

2901
				if ( ! warned ) {
T
tschw 已提交
2902

2903 2904
					console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
					warned = true;
T
tschw 已提交
2905

2906
				}
T
tschw 已提交
2907

2908
				texture = texture.texture;
T
tschw 已提交
2909

2910
			}
T
tschw 已提交
2911

2912
			setTexture2D( texture, slot );
T
tschw 已提交
2913

2914
		};
T
tschw 已提交
2915

2916
	}() );
T
tschw 已提交
2917

2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
	this.setTexture = ( function() {

		var warned = false;

		return function( texture, slot ) {

			if ( ! warned ) {

				console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
				warned = true;

			}

			_this.setTexture2D( texture, slot );

		};

	}() );

	this.setTextureCube = ( function() {

		var warned = false;

		return function( texture, slot ) {

			// backwards compatibility: peel texture.texture
			if ( texture instanceof THREE.WebGLRenderTargetCube ) {

				if ( ! warned ) {

					console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
					warned = true;

				}

				texture = texture.texture;

			}

			// currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
			// TODO: unify these code paths
			if ( texture instanceof THREE.CubeTexture ||
				 ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

				// CompressedTexture can have Array in image :/

				// this function alone should take care of cube textures
				setTextureCube( texture, slot );

			} else {

				// assumed: texture property of THREE.WebGLRenderTargetCube

				setTextureCubeDynamic( texture, slot );

			}

		};

	}() );
T
tschw 已提交
2978

M
Mr.doob 已提交
2979 2980
	// Render targets

2981 2982
	// Setup storage for target texture and bind it to correct framebuffer
	function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
M
Mr.doob 已提交
2983

2984 2985 2986
		var glFormat = paramThreeToGL( renderTarget.texture.format );
		var glType = paramThreeToGL( renderTarget.texture.type );
		state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
M
Mr.doob 已提交
2987
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
2988 2989
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
M
Mr.doob 已提交
2990

M
Mr.doob 已提交
2991
	}
M
Mr.doob 已提交
2992

2993 2994
	// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
	function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
M
Mr.doob 已提交
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009

		_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 );

		} 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 {

3010
			// FIXME: We don't support !depth !stencil
M
Mr.doob 已提交
3011 3012 3013 3014
			_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );

		}

3015
		_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
M
Mr.doob 已提交
3016

M
Mr.doob 已提交
3017
	}
M
Mr.doob 已提交
3018

3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
	// Setup resources for a Depth Texture for a FBO (needs an extension)
	function setupDepthTexture ( framebuffer, renderTarget ) {

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
		if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');

		_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );

		if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) {

			throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');

		}

		// upload an empty depth texture with framebuffer size
		if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
				renderTarget.depthTexture.image.width !== renderTarget.width ||
				renderTarget.depthTexture.image.height !== renderTarget.height ) {
			renderTarget.depthTexture.image.width = renderTarget.width;
			renderTarget.depthTexture.image.height = renderTarget.height;
			renderTarget.depthTexture.needsUpdate = true;
		}

3042
		_this.setTexture2D( renderTarget.depthTexture, 0 );
3043 3044 3045 3046 3047 3048

		var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
		_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );

	}

3049
	// Setup GL resources for a non-texture depth buffer
M
Marius Kintel 已提交
3050
	function setupDepthRenderbuffer( renderTarget ) {
M
Mr.doob 已提交
3051

3052
		var renderTargetProperties = properties.get( renderTarget );
M
Mr.doob 已提交
3053 3054

		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
M
Mr.doob 已提交
3055

3056
		if ( renderTarget.depthTexture ) {
M
Mr.doob 已提交
3057

3058
			if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
M
Mr.doob 已提交
3059

3060 3061 3062
			setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );

		} else {
M
Mr.doob 已提交
3063

3064
			if ( isCube ) {
M
Mr.doob 已提交
3065

3066
				renderTargetProperties.__webglDepthbuffer = [];
B
Ben Adams 已提交
3067

3068 3069 3070 3071 3072
				for ( var i = 0; i < 6; i ++ ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
					renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
					setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
M
Mr.doob 已提交
3073

3074 3075 3076 3077 3078 3079 3080 3081 3082
				}

			} else {

				_gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
				renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
				setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );

			}
M
Mr.doob 已提交
3083

3084
		}
M
Mr.doob 已提交
3085

M
Marius Kintel 已提交
3086
		_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
M
Mr.doob 已提交
3087

M
Mr.doob 已提交
3088
	}
M
Mr.doob 已提交
3089

3090
	// Set up GL resources for the render target
M
Marius Kintel 已提交
3091
	function setupRenderTarget( renderTarget ) {
M
Mr.doob 已提交
3092

3093 3094
		var renderTargetProperties = properties.get( renderTarget );
		var textureProperties = properties.get( renderTarget.texture );
M
Mr.doob 已提交
3095

3096
		renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
M
Mr.doob 已提交
3097

3098
		textureProperties.__webglTexture = _gl.createTexture();
M
Mr.doob 已提交
3099

3100
		_infoMemory.textures ++;
M
Mr.doob 已提交
3101

3102 3103
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
		var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
M
Mr.doob 已提交
3104

3105
		// Setup framebuffer
M
Mr.doob 已提交
3106

3107
		if ( isCube ) {
M
Mr.doob 已提交
3108

3109
			renderTargetProperties.__webglFramebuffer = [];
M
Mr.doob 已提交
3110

3111
			for ( var i = 0; i < 6; i ++ ) {
M
Mr.doob 已提交
3112

3113
				renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
M
Mr.doob 已提交
3114

3115
			}
M
Mr.doob 已提交
3116

3117
		} else {
M
Mr.doob 已提交
3118

3119
			renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
M
Mr.doob 已提交
3120

3121
		}
M
Mr.doob 已提交
3122

3123
		// Setup color buffer
M
Mr.doob 已提交
3124

3125
		if ( isCube ) {
M
Mr.doob 已提交
3126

3127 3128
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
M
Mr.doob 已提交
3129

3130
			for ( var i = 0; i < 6; i ++ ) {
M
Mr.doob 已提交
3131

3132
				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
M
Mr.doob 已提交
3133 3134 3135

			}

3136 3137
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
			state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
M
Mr.doob 已提交
3138

3139
		} else {
M
Mr.doob 已提交
3140

3141 3142 3143
			state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
			setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
			setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
M
Mr.doob 已提交
3144

3145 3146
			if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
			state.bindTexture( _gl.TEXTURE_2D, null );
M
Mr.doob 已提交
3147

3148
		}
M
Mr.doob 已提交
3149

3150
		// Setup depth and stencil buffers
3151

3152
		if ( renderTarget.depthBuffer ) {
M
Mr.doob 已提交
3153

M
Marius Kintel 已提交
3154
			setupDepthRenderbuffer( renderTarget );
M
Mr.doob 已提交
3155

3156
		}
M
Mr.doob 已提交
3157

3158
	}
M
Mr.doob 已提交
3159

3160 3161 3162 3163
	this.getCurrentRenderTarget = function() {

		return _currentRenderTarget;

M
Michael Herzog 已提交
3164
	};
3165

3166
	this.setRenderTarget = function ( renderTarget ) {
M
Mr.doob 已提交
3167

3168 3169
		_currentRenderTarget = renderTarget;

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

M
Marius Kintel 已提交
3172
			setupRenderTarget( renderTarget );
M
Mr.doob 已提交
3173 3174 3175

		}

3176
		var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
3177
		var framebuffer;
M
Mr.doob 已提交
3178 3179 3180

		if ( renderTarget ) {

3181
			var renderTargetProperties = properties.get( renderTarget );
F
Fordy 已提交
3182

M
Mr.doob 已提交
3183 3184
			if ( isCube ) {

3185
				framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
M
Mr.doob 已提交
3186 3187 3188

			} else {

3189
				framebuffer = renderTargetProperties.__webglFramebuffer;
M
Mr.doob 已提交
3190 3191 3192

			}

3193 3194
			_currentScissor.copy( renderTarget.scissor );
			_currentScissorTest = renderTarget.scissorTest;
3195

3196
			_currentViewport.copy( renderTarget.viewport );
M
Mr.doob 已提交
3197 3198 3199 3200 3201

		} else {

			framebuffer = null;

3202
			_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
3203
			_currentScissorTest = _scissorTest;
3204

3205
			_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
M
Mr.doob 已提交
3206 3207 3208

		}

M
Mr.doob 已提交
3209
		if ( _currentFramebuffer !== framebuffer ) {
M
Mr.doob 已提交
3210 3211 3212 3213 3214 3215

			_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
			_currentFramebuffer = framebuffer;

		}

3216 3217
		state.scissor( _currentScissor );
		state.setScissorTest( _currentScissorTest );
3218

3219
		state.viewport( _currentViewport );
3220

M
Mr.doob 已提交
3221 3222 3223
		if ( isCube ) {

			var textureProperties = properties.get( renderTarget.texture );
3224
			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
M
Mr.doob 已提交
3225 3226 3227

		}

M
Mr.doob 已提交
3228 3229
	};

M
Mr.doob 已提交
3230
	this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
3231

M
Mr.doob 已提交
3232
		if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
3233

3234
			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
G
gero3 已提交
3235
			return;
3236

G
gero3 已提交
3237
		}
3238

M
Mr.doob 已提交
3239
		var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
3240

M
Mr.doob 已提交
3241
		if ( framebuffer ) {
3242

G
gero3 已提交
3243
			var restore = false;
3244

M
Mr.doob 已提交
3245
			if ( framebuffer !== _currentFramebuffer ) {
3246

M
Mr.doob 已提交
3247
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
3248

G
gero3 已提交
3249
				restore = true;
3250

G
gero3 已提交
3251
			}
3252

M
Mr.doob 已提交
3253
			try {
3254

M
Mr.doob 已提交
3255
				var texture = renderTarget.texture;
3256

M
Michael Herzog 已提交
3257
				if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
3258

M
Mr.doob 已提交
3259 3260
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
					return;
3261

M
Mr.doob 已提交
3262
				}
3263

M
Michael Herzog 已提交
3264 3265 3266 3267
				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' ) ) ) {
3268

M
Mr.doob 已提交
3269 3270
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
					return;
3271

M
Mr.doob 已提交
3272
				}
3273

M
Mr.doob 已提交
3274
				if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
3275

3276 3277
					// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)

3278
					if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
3279 3280 3281 3282

						_gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );

					}
3283

M
Mr.doob 已提交
3284
				} else {
M
Mr.doob 已提交
3285

M
Mr.doob 已提交
3286 3287 3288
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

				}
M
Mr.doob 已提交
3289

M
Mr.doob 已提交
3290
			} finally {
M
Mr.doob 已提交
3291

M
Mr.doob 已提交
3292 3293 3294
				if ( restore ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
M
Mr.doob 已提交
3295

M
Mr.doob 已提交
3296 3297 3298
				}

			}
M
Mr.doob 已提交
3299 3300 3301

		}

M
Mr.doob 已提交
3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312
	};

	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 已提交
3313
	}
M
Mr.doob 已提交
3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326

	// 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 已提交
3327
	}
M
Mr.doob 已提交
3328 3329 3330 3331 3332

	// Map three.js constants to WebGL constants

	function paramThreeToGL ( p ) {

3333 3334
		var extension;

M
Mr.doob 已提交
3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
		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;

3359 3360 3361 3362 3363 3364 3365 3366
		extension = extensions.get( 'OES_texture_half_float' );

		if ( extension !== null ) {

			if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;

		}

M
Mr.doob 已提交
3367 3368 3369 3370 3371
		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;
3372
		if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT;
M
Mr.doob 已提交
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390

		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;

3391
		extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
M
Mr.doob 已提交
3392

3393 3394 3395 3396 3397 3398
		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 已提交
3399 3400 3401

		}

3402 3403 3404
		extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

		if ( extension !== null ) {
P
Pierre Lepers 已提交
3405

3406 3407 3408 3409
			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 已提交
3410 3411 3412

		}

3413 3414 3415 3416 3417 3418 3419 3420
		extension = extensions.get( 'WEBGL_compressed_texture_etc1' );

		if ( extension !== null ) {

			if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;

		}

3421 3422 3423
		extension = extensions.get( 'EXT_blend_minmax' );

		if ( extension !== null ) {
3424

3425 3426
			if ( p === THREE.MinEquation ) return extension.MIN_EXT;
			if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
3427 3428 3429

		}

M
Mr.doob 已提交
3430 3431
		return 0;

M
Mr.doob 已提交
3432
	}
M
Mr.doob 已提交
3433 3434

};