WebGLRenderer.js 68.5 KB
Newer Older
M
Mr.doob 已提交
1
import { REVISION, MaxEquation, MinEquation, RGB_ETC1_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT1_Format, RGB_S3TC_DXT1_Format, SrcAlphaSaturateFactor, OneMinusDstColorFactor, DstColorFactor, OneMinusDstAlphaFactor, DstAlphaFactor, OneMinusSrcAlphaFactor, SrcAlphaFactor, OneMinusSrcColorFactor, SrcColorFactor, OneFactor, ZeroFactor, ReverseSubtractEquation, SubtractEquation, AddEquation, DepthFormat, DepthStencilFormat, LuminanceAlphaFormat, LuminanceFormat, RGBAFormat, RGBFormat, AlphaFormat, HalfFloatType, FloatType, UnsignedIntType, IntType, UnsignedShortType, ShortType, ByteType, UnsignedInt248Type, UnsignedShort565Type, UnsignedShort5551Type, UnsignedShort4444Type, UnsignedByteType, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestFilter, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, FrontFaceDirectionCW, NoBlending, BackSide, DoubleSide, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, NoColors, FlatShading, LinearToneMapping } from '../constants';
R
Rich Harris 已提交
2 3
import { Matrix4 } from '../math/Matrix4';
import { WebGLUniforms } from './webgl/WebGLUniforms';
4
import { UniformsUtils } from './shaders/UniformsUtils';
R
Rich Harris 已提交
5 6 7 8 9 10
import { ShaderLib } from './shaders/ShaderLib';
import { LensFlarePlugin } from './webgl/plugins/LensFlarePlugin';
import { SpritePlugin } from './webgl/plugins/SpritePlugin';
import { WebGLShadowMap } from './webgl/WebGLShadowMap';
import { ShaderMaterial } from '../materials/ShaderMaterial';
import { Mesh } from '../objects/Mesh';
M
Mr.doob 已提交
11 12
import { BoxBufferGeometry } from '../geometries/BoxGeometry';
import { PlaneBufferGeometry } from '../geometries/PlaneGeometry';
R
Rich Harris 已提交
13 14 15
import { MeshBasicMaterial } from '../materials/MeshBasicMaterial';
import { PerspectiveCamera } from '../cameras/PerspectiveCamera';
import { OrthographicCamera } from '../cameras/OrthographicCamera';
16
import { WebGLAttributes } from './webgl/WebGLAttributes';
R
Rich Harris 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import { WebGLIndexedBufferRenderer } from './webgl/WebGLIndexedBufferRenderer';
import { WebGLBufferRenderer } from './webgl/WebGLBufferRenderer';
import { WebGLLights } from './webgl/WebGLLights';
import { WebGLPrograms } from './webgl/WebGLPrograms';
import { WebGLObjects } from './webgl/WebGLObjects';
import { WebGLTextures } from './webgl/WebGLTextures';
import { WebGLProperties } from './webgl/WebGLProperties';
import { WebGLState } from './webgl/WebGLState';
import { WebGLCapabilities } from './webgl/WebGLCapabilities';
import { BufferGeometry } from '../core/BufferGeometry';
import { WebGLExtensions } from './webgl/WebGLExtensions';
import { Vector3 } from '../math/Vector3';
import { Sphere } from '../math/Sphere';
import { WebGLClipping } from './webgl/WebGLClipping';
import { Frustum } from '../math/Frustum';
import { Vector4 } from '../math/Vector4';
import { Color } from '../math/Color';

M
Mr.doob 已提交
35 36 37 38 39
/**
 * @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 已提交
40
 * @author tschw
M
Mr.doob 已提交
41 42
 */

M
Mr.doob 已提交
43
function WebGLRenderer( parameters ) {
M
Mr.doob 已提交
44

M
Mr.doob 已提交
45
	console.log( 'THREE.WebGLRenderer', REVISION );
M
Mr.doob 已提交
46 47 48

	parameters = parameters || {};

E
Eli Grey 已提交
49
	var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
50
		_context = parameters.context !== undefined ? parameters.context : null,
M
Mr.doob 已提交
51

52 53 54 55 56 57
		_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
		_depth = parameters.depth !== undefined ? parameters.depth : true,
		_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
		_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
		_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
		_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
M
Mr.doob 已提交
58

M
Mr.doob 已提交
59
	var lights = [];
M
Mr.doob 已提交
60

O
OpenShift guest 已提交
61
	var opaqueObjects = [];
M
Mr.doob 已提交
62
	var opaqueObjectsLastIndex = - 1;
63
	var transparentObjects = [];
M
Mr.doob 已提交
64
	var transparentObjectsLastIndex = - 1;
65

66 67
	var morphInfluences = new Float32Array( 8 );

M
Mr.doob 已提交
68 69 70
	var sprites = [];
	var lensFlares = [];

M
Mr.doob 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	// 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 已提交
87 88 89 90 91
	// user-defined clipping

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

M
Mr.doob 已提交
92 93
	// physically based shading

94
	this.gammaFactor = 2.0;	// for backwards compatibility
M
Mr.doob 已提交
95 96 97
	this.gammaInput = false;
	this.gammaOutput = false;

98 99
	// physical lights

100
	this.physicallyCorrectLights = false;
101

B
Ben Houston 已提交
102 103
	// tone mapping

R
Rich Harris 已提交
104
	this.toneMapping = LinearToneMapping;
B
Ben Houston 已提交
105 106 107
	this.toneMappingExposure = 1.0;
	this.toneMappingWhitePoint = 1.0;

M
Mr.doob 已提交
108 109 110 111 112 113 114 115 116
	// morphs

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

	// internal properties

	var _this = this,

117
		// internal state cache
M
Mr.doob 已提交
118

119 120 121 122 123 124
		_currentProgram = null,
		_currentRenderTarget = null,
		_currentFramebuffer = null,
		_currentMaterialId = - 1,
		_currentGeometryProgram = '',
		_currentCamera = null,
M
Mr.doob 已提交
125

126 127
		_currentScissor = new Vector4(),
		_currentScissorTest = null,
128

129
		_currentViewport = new Vector4(),
130

131
		//
132

133
		_usedTextureUnits = 0,
M
Mr.doob 已提交
134

135
		//
M
Mr.doob 已提交
136

137 138
		_clearColor = new Color( 0x000000 ),
		_clearAlpha = 0,
M
Mr.doob 已提交
139

140 141
		_width = _canvas.width,
		_height = _canvas.height,
M
Mr.doob 已提交
142

143
		_pixelRatio = 1,
M
Mr.doob 已提交
144

145 146
		_scissor = new Vector4( 0, 0, _width, _height ),
		_scissorTest = false,
147

148
		_viewport = new Vector4( 0, 0, _width, _height ),
149

150
		// frustum
M
Mr.doob 已提交
151

152
		_frustum = new Frustum(),
M
Mr.doob 已提交
153

154
		// clipping
T
tschw 已提交
155

156 157 158
		_clipping = new WebGLClipping(),
		_clippingEnabled = false,
		_localClippingEnabled = false,
T
tschw 已提交
159

160
		_sphere = new Sphere(),
T
tschw 已提交
161

162
		// camera matrices cache
M
Mr.doob 已提交
163

164
		_projScreenMatrix = new Matrix4(),
M
Mr.doob 已提交
165

A
aardgoose 已提交
166
		_vector3 = new Vector3(),
167
		_matrix4 = new Matrix4(),
A
aardgoose 已提交
168
		_matrix42 = new Matrix4(),
M
Mr.doob 已提交
169

170
		// light arrays cache
M
Mr.doob 已提交
171

172
		_lights = {
M
Mr.doob 已提交
173

174
			hash: '',
175

M
Mr.doob 已提交
176 177 178 179 180 181 182 183 184 185 186 187
			ambient: [ 0, 0, 0 ],
			directional: [],
			directionalShadowMap: [],
			directionalShadowMatrix: [],
			spot: [],
			spotShadowMap: [],
			spotShadowMatrix: [],
			rectArea: [],
			point: [],
			pointShadowMap: [],
			pointShadowMatrix: [],
			hemi: [],
188

189
			shadows: []
M
Mr.doob 已提交
190

191
		},
192

193
		// info
M
Mr.doob 已提交
194

195
		_infoRender = {
196

197 198 199 200
			calls: 0,
			vertices: 0,
			faces: 0,
			points: 0
201

202
		};
M
Mr.doob 已提交
203

M
Mr.doob 已提交
204
	this.info = {
205

M
Mr.doob 已提交
206
		render: _infoRender,
207 208 209 210 211 212
		memory: {

			geometries: 0,
			textures: 0

		},
213
		programs: null
M
Mr.doob 已提交
214 215

	};
216

217

M
Mr.doob 已提交
218 219 220 221
	// initialize

	var _gl;

M
Mr.doob 已提交
222 223
	try {

224
		var contextAttributes = {
M
Mr.doob 已提交
225 226 227 228 229 230 231 232
			alpha: _alpha,
			depth: _depth,
			stencil: _stencil,
			antialias: _antialias,
			premultipliedAlpha: _premultipliedAlpha,
			preserveDrawingBuffer: _preserveDrawingBuffer
		};

233
		_gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
M
Mr.doob 已提交
234 235 236

		if ( _gl === null ) {

G
gero3 已提交
237
			if ( _canvas.getContext( 'webgl' ) !== null ) {
238 239 240 241 242 243 244 245

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

			} else {

				throw 'Error creating WebGL context.';

			}
M
Mr.doob 已提交
246 247 248

		}

249 250 251 252 253 254 255 256 257 258 259 260
		// Some experimental-webgl implementations do not have getShaderPrecisionFormat

		if ( _gl.getShaderPrecisionFormat === undefined ) {

			_gl.getShaderPrecisionFormat = function () {

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

			};

		}

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

M
Mr.doob 已提交
263 264
	} catch ( error ) {

265
		console.error( 'THREE.WebGLRenderer: ' + error );
M
Mr.doob 已提交
266 267 268

	}

R
Rich Harris 已提交
269
	var extensions = new WebGLExtensions( _gl );
270

271
	extensions.get( 'WEBGL_depth_texture' );
272 273
	extensions.get( 'OES_texture_float' );
	extensions.get( 'OES_texture_float_linear' );
274 275
	extensions.get( 'OES_texture_half_float' );
	extensions.get( 'OES_texture_half_float_linear' );
276
	extensions.get( 'OES_standard_derivatives' );
B
Ben Adams 已提交
277
	extensions.get( 'ANGLE_instanced_arrays' );
278

279 280
	if ( extensions.get( 'OES_element_index_uint' ) ) {

R
Rich Harris 已提交
281
		BufferGeometry.MaxIndex = 4294967296;
282 283 284

	}

R
Rich Harris 已提交
285
	var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
M
Mr.doob 已提交
286

R
Rich Harris 已提交
287
	var state = new WebGLState( _gl, extensions, paramThreeToGL );
288

R
Rich Harris 已提交
289 290
	var properties = new WebGLProperties();
	var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
291 292
	var attributes = new WebGLAttributes( _gl, properties );
	var objects = new WebGLObjects( _gl, attributes, properties, this.info );
R
Rich Harris 已提交
293 294
	var programCache = new WebGLPrograms( this, capabilities );
	var lightCache = new WebGLLights();
295

296 297
	this.info.programs = programCache.programs;

R
Rich Harris 已提交
298 299
	var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
	var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
300

M
Mr.doob 已提交
301 302
	//

M
Mr.doob 已提交
303 304
	var backgroundPlaneCamera, backgroundPlaneMesh;
	var backgroundBoxCamera, backgroundBoxMesh;
M
Mr.doob 已提交
305 306 307

	//

308 309
	function getTargetPixelRatio() {

310
		return _currentRenderTarget === null ? _pixelRatio : 1;
311 312 313

	}

314
	function setDefaultGLState() {
M
Mr.doob 已提交
315

M
Mr.doob 已提交
316
		state.init();
M
Mr.doob 已提交
317

318 319
		state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
		state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
M
Mr.doob 已提交
320

321
		state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
M
Mr.doob 已提交
322

323
	}
324

325
	function resetGLState() {
326 327 328 329

		_currentProgram = null;
		_currentCamera = null;

330
		_currentGeometryProgram = '';
331 332
		_currentMaterialId = - 1;

M
Mr.doob 已提交
333 334
		state.reset();

335
	}
M
Mr.doob 已提交
336 337 338 339

	setDefaultGLState();

	this.context = _gl;
M
Mr.doob 已提交
340
	this.capabilities = capabilities;
341
	this.extensions = extensions;
342
	this.properties = properties;
M
Mr.doob 已提交
343
	this.state = state;
M
Mr.doob 已提交
344

M
Mr.doob 已提交
345 346
	// shadow map

R
Rich Harris 已提交
347
	var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
M
Mr.doob 已提交
348

349
	this.shadowMap = shadowMap;
M
Mr.doob 已提交
350

M
Mr.doob 已提交
351

M
Mr.doob 已提交
352 353
	// Plugins

R
Rich Harris 已提交
354 355
	var spritePlugin = new SpritePlugin( this, sprites );
	var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
M
Mr.doob 已提交
356

M
Mr.doob 已提交
357 358 359 360 361 362 363 364
	// API

	this.getContext = function () {

		return _gl;

	};

365 366 367 368 369 370
	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

371 372 373 374 375 376
	this.forceContextLoss = function () {

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

	};

377
	this.getMaxAnisotropy = function () {
378

379
		return capabilities.getMaxAnisotropy();
380

381
	};
M
Mr.doob 已提交
382 383 384

	this.getPrecision = function () {

G
gero3 已提交
385
		return capabilities.precision;
M
Mr.doob 已提交
386 387 388

	};

389 390
	this.getPixelRatio = function () {

391
		return _pixelRatio;
392 393 394 395 396

	};

	this.setPixelRatio = function ( value ) {

397 398 399 400 401
		if ( value === undefined ) return;

		_pixelRatio = value;

		this.setSize( _viewport.z, _viewport.w, false );
402 403 404

	};

405 406 407
	this.getSize = function () {

		return {
408 409
			width: _width,
			height: _height
410 411 412 413
		};

	};

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

416 417 418
		_width = width;
		_height = height;

419 420
		_canvas.width = width * _pixelRatio;
		_canvas.height = height * _pixelRatio;
421

422
		if ( updateStyle !== false ) {
423

G
gero3 已提交
424 425
			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';
426

G
gero3 已提交
427
		}
M
Mr.doob 已提交
428

429
		this.setViewport( 0, 0, width, height );
M
Mr.doob 已提交
430 431 432 433 434

	};

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

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

	};

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

441
		state.scissor( _scissor.set( x, y, width, height ) );
M
Mr.doob 已提交
442 443 444

	};

445 446
	this.setScissorTest = function ( boolean ) {

447
		state.setScissorTest( _scissorTest = boolean );
M
Mr.doob 已提交
448 449 450 451 452

	};

	// Clearing

M
Mr.doob 已提交
453
	this.getClearColor = function () {
M
Mr.doob 已提交
454

M
Mr.doob 已提交
455
		return _clearColor;
M
Mr.doob 已提交
456 457 458

	};

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

M
Mr.doob 已提交
461
		_clearColor.set( color );
462

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

465
		state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
M
Mr.doob 已提交
466 467 468

	};

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

M
Mr.doob 已提交
471
		return _clearAlpha;
M
Mr.doob 已提交
472 473 474

	};

M
Mr.doob 已提交
475
	this.setClearAlpha = function ( alpha ) {
M
Mr.doob 已提交
476

M
Mr.doob 已提交
477
		_clearAlpha = alpha;
M
Mr.doob 已提交
478

479
		state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
M
Mr.doob 已提交
480 481 482 483 484 485 486 487 488 489 490 491

	};

	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 );
492 493 494 495 496

	};

	this.clearColor = function () {

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

	};

	this.clearDepth = function () {

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

	};

	this.clearStencil = function () {

M
Mr.doob 已提交
509
		this.clear( false, false, true );
M
Mr.doob 已提交
510 511 512 513 514 515 516 517 518 519

	};

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

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

	};

M
Mr.doob 已提交
520 521
	// Reset

522
	this.resetGLState = resetGLState;
M
Mr.doob 已提交
523

M
Mr.doob 已提交
524
	this.dispose = function () {
D
dubejf 已提交
525

526
		transparentObjects = [];
M
Mr.doob 已提交
527
		transparentObjectsLastIndex = - 1;
528
		opaqueObjects = [];
M
Mr.doob 已提交
529
		opaqueObjectsLastIndex = - 1;
530

D
dubejf 已提交
531 532 533 534
		_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );

	};

M
Mr.doob 已提交
535
	// Events
M
Mr.doob 已提交
536

D
dubejf 已提交
537 538 539 540 541 542 543 544 545
	function onContextLost( event ) {

		event.preventDefault();

		resetGLState();
		setDefaultGLState();

		properties.clear();

M
Mr.doob 已提交
546
	}
D
dubejf 已提交
547

548
	function onMaterialDispose( event ) {
M
Mr.doob 已提交
549 550 551 552 553 554 555

		var material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

556
	}
M
Mr.doob 已提交
557 558 559

	// Buffer deallocation

560
	function deallocateMaterial( material ) {
M
Mr.doob 已提交
561

562 563
		releaseMaterialProgramReference( material );

564
		properties.remove( material );
565

566
	}
567 568


569
	function releaseMaterialProgramReference( material ) {
570

571
		var programInfo = properties.get( material ).program;
M
Mr.doob 已提交
572 573 574

		material.program = undefined;

575
		if ( programInfo !== undefined ) {
M
Mr.doob 已提交
576

577
			programCache.releaseProgram( programInfo );
M
Mr.doob 已提交
578

M
Mr.doob 已提交
579 580
		}

581
	}
M
Mr.doob 已提交
582 583 584

	// Buffer rendering

M
Mr.doob 已提交
585 586 587 588 589 590 591 592 593 594
	function renderObjectImmediate( object, program, material ) {

		object.render( function ( object ) {

			_this.renderBufferImmediate( object, program, material );

		} );

	}

M
Mr.doob 已提交
595 596
	this.renderBufferImmediate = function ( object, program, material ) {

597
		state.initAttributes();
598

599
		var buffers = properties.get( object );
600

601 602 603 604
		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 已提交
605

606
		var programAttributes = program.getAttributes();
607

M
Mr.doob 已提交
608 609
		if ( object.hasPositions ) {

610
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
M
Mr.doob 已提交
611
			_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
612

613 614
			state.enableAttribute( programAttributes.position );
			_gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
615 616 617 618 619

		}

		if ( object.hasNormals ) {

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

622
			if ( ! material.isMeshPhongMaterial &&
623
				! material.isMeshStandardMaterial &&
624
				! material.isMeshNormalMaterial &&
625
				material.shading === FlatShading ) {
M
Mr.doob 已提交
626

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

629
					var array = object.normalArray;
M
Mr.doob 已提交
630

631 632 633
					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 已提交
634

635 636 637
					array[ i + 0 ] = nx;
					array[ i + 1 ] = ny;
					array[ i + 2 ] = nz;
M
Mr.doob 已提交
638

639 640 641
					array[ i + 3 ] = nx;
					array[ i + 4 ] = ny;
					array[ i + 5 ] = nz;
M
Mr.doob 已提交
642

643 644 645
					array[ i + 6 ] = nx;
					array[ i + 7 ] = ny;
					array[ i + 8 ] = nz;
M
Mr.doob 已提交
646 647 648 649 650 651

				}

			}

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

653
			state.enableAttribute( programAttributes.normal );
654

655
			_gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
656 657 658 659 660

		}

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

661
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
M
Mr.doob 已提交
662
			_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
663

664
			state.enableAttribute( programAttributes.uv );
665

666
			_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
667 668 669

		}

R
Rich Harris 已提交
670
		if ( object.hasColors && material.vertexColors !== NoColors ) {
M
Mr.doob 已提交
671

672
			_gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
M
Mr.doob 已提交
673
			_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
674

675
			state.enableAttribute( programAttributes.color );
676

677
			_gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
M
Mr.doob 已提交
678 679 680

		}

681
		state.disableUnusedAttributes();
682

M
Mr.doob 已提交
683 684 685 686 687 688
		_gl.drawArrays( _gl.TRIANGLES, 0, object.count );

		object.count = 0;

	};

M
Mr.doob 已提交
689 690
	var program, geometryProgram, updateBuffers;

691
	this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
692

M
Mr.doob 已提交
693 694
		setMaterial( material );

M
Mr.doob 已提交
695 696
		program = setProgram( camera, fog, material, object );
		geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
M
Mr.doob 已提交
697

M
Mr.doob 已提交
698
		updateBuffers = false;
M
Mr.doob 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712

		if ( geometryProgram !== _currentGeometryProgram ) {

			_currentGeometryProgram = geometryProgram;
			updateBuffers = true;

		}

		// morph targets

		var morphTargetInfluences = object.morphTargetInfluences;

		if ( morphTargetInfluences !== undefined ) {

M
Mr.doob 已提交
713 714
			// TODO Remove allocations

M
Mr.doob 已提交
715 716 717 718 719 720 721 722 723
			var activeInfluences = [];

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

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

			}

724
			activeInfluences.sort( absNumericalSort );
M
Mr.doob 已提交
725 726 727 728 729 730 731

			if ( activeInfluences.length > 8 ) {

				activeInfluences.length = 8;

			}

732 733
			var morphAttributes = geometry.morphAttributes;

M
Mr.doob 已提交
734 735 736 737 738 739 740
			for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {

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

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

741
					var index = influence[ 1 ];
M
Mr.doob 已提交
742

743 744
					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 已提交
745 746 747

				} else {

748 749
					if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
					if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
M
Mr.doob 已提交
750 751 752 753 754

				}

			}

755 756 757 758 759 760
			for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {

				morphInfluences[ i ] = 0.0;

			}

M
Mr.doob 已提交
761
			program.getUniforms().setValue( _gl, 'morphTargetInfluences', morphInfluences );
M
Mr.doob 已提交
762 763 764 765 766

			updateBuffers = true;

		}

767 768
		//

769
		var index = geometry.index;
770
		var position = geometry.attributes.position;
771
		var rangeFactor = 1;
772

773 774
		if ( material.wireframe === true ) {

775
			index = objects.getWireframeAttribute( geometry );
776
			rangeFactor = 2;
777 778 779

		}

M
Mr.doob 已提交
780
		var renderer = bufferRenderer;
781

782
		if ( index !== null ) {
783

784 785
			renderer = indexedBufferRenderer;
			renderer.setIndex( index );
786

787
		}
M
Mr.doob 已提交
788

789
		if ( updateBuffers ) {
M
Mr.doob 已提交
790

791
			setupVertexAttributes( material, program, geometry );
M
Mr.doob 已提交
792

793
			if ( index !== null ) {
794

795
				_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).__webglBuffer );
796 797 798

			}

799
		}
800

801 802
		//

803
		var dataCount = 0;
804

M
Mr.doob 已提交
805
		if ( index !== null ) {
806

M
Mr.doob 已提交
807
			dataCount = index.count;
808

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

M
Mr.doob 已提交
811
			dataCount = position.count;
812

M
Mr.doob 已提交
813
		}
814

M
Mr.doob 已提交
815 816
		var rangeStart = geometry.drawRange.start * rangeFactor;
		var rangeCount = geometry.drawRange.count * rangeFactor;
817

M
Mr.doob 已提交
818 819
		var groupStart = group !== null ? group.start * rangeFactor : 0;
		var groupCount = group !== null ? group.count * rangeFactor : Infinity;
820

M
Mr.doob 已提交
821 822
		var drawStart = Math.max( rangeStart, groupStart );
		var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
M
Mr.doob 已提交
823 824 825

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

826 827
		if ( drawCount === 0 ) return;

M
Mr.doob 已提交
828
		//
829

830
		if ( object.isMesh ) {
831

832
			if ( material.wireframe === true ) {
833

834
				state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
835
				renderer.setMode( _gl.LINES );
836

837
			} else {
M
Mr.doob 已提交
838 839

				switch ( object.drawMode ) {
840

R
Rich Harris 已提交
841
					case TrianglesDrawMode:
B
Ben Adams 已提交
842 843 844
						renderer.setMode( _gl.TRIANGLES );
						break;

R
Rich Harris 已提交
845
					case TriangleStripDrawMode:
B
Ben Adams 已提交
846 847 848
						renderer.setMode( _gl.TRIANGLE_STRIP );
						break;

R
Rich Harris 已提交
849
					case TriangleFanDrawMode:
B
Ben Adams 已提交
850 851 852 853
						renderer.setMode( _gl.TRIANGLE_FAN );
						break;

				}
854

855
			}
856

857

858
		} else if ( object.isLine ) {
859

860
			var lineWidth = material.linewidth;
861

862
			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
863

864
			state.setLineWidth( lineWidth * getTargetPixelRatio() );
865

866
			if ( object.isLineSegments ) {
867

868
				renderer.setMode( _gl.LINES );
869

870 871 872 873
			} else if ( object.isLineLoop ) {

				renderer.setMode( _gl.LINE_LOOP );

874
			} else {
875

876
				renderer.setMode( _gl.LINE_STRIP );
877 878

			}
M
Mr.doob 已提交
879

880
		} else if ( object.isPoints ) {
881 882

			renderer.setMode( _gl.POINTS );
883 884

		}
885

T
Takahiro 已提交
886
		if ( geometry && geometry.isInstancedBufferGeometry ) {
M
Mr.doob 已提交
887 888 889

			if ( geometry.maxInstancedCount > 0 ) {

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

J
jfranc 已提交
892
			}
893 894 895

		} else {

M
Mr.doob 已提交
896
			renderer.render( drawStart, drawCount );
897

M
Mr.doob 已提交
898 899 900 901
		}

	};

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

M
Mr.doob 已提交
904
		var extension;
B
Ben Adams 已提交
905

T
Takahiro 已提交
906
		if ( geometry && geometry.isInstancedBufferGeometry ) {
B
Ben Adams 已提交
907

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

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

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

M
Mr.doob 已提交
915 916 917
			}

		}
B
Ben Adams 已提交
918

919 920
		if ( startIndex === undefined ) startIndex = 0;

921 922
		state.initAttributes();

923
		var geometryAttributes = geometry.attributes;
924

925
		var programAttributes = program.getAttributes();
926

927
		var materialDefaultAttributeValues = material.defaultAttributeValues;
928

929
		for ( var name in programAttributes ) {
930

931
			var programAttribute = programAttributes[ name ];
M
Mr.doob 已提交
932

M
Mr.doob 已提交
933
			if ( programAttribute >= 0 ) {
M
Mr.doob 已提交
934

935
				var geometryAttribute = geometryAttributes[ name ];
936

M
Mr.doob 已提交
937
				if ( geometryAttribute !== undefined ) {
M
Mr.doob 已提交
938

939
					var normalized = geometryAttribute.normalized;
940
					var size = geometryAttribute.itemSize;
941

942
					var attributeProperties = attributes.get( geometryAttribute );
943

944 945 946
					var buffer = attributeProperties.__webglBuffer;
					var type = attributeProperties.type;
					var bytesPerElement = attributeProperties.bytesPerElement;
947

A
aardgoose 已提交
948
					if ( geometryAttribute.isInterleavedBufferAttribute ) {
949

M
Mr.doob 已提交
950 951 952 953
						var data = geometryAttribute.data;
						var stride = data.stride;
						var offset = geometryAttribute.offset;

T
Takahiro 已提交
954
						if ( data && data.isInstancedInterleavedBuffer ) {
M
Mr.doob 已提交
955

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

M
Mr.doob 已提交
958
							if ( geometry.maxInstancedCount === undefined ) {
959

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

M
Mr.doob 已提交
962
							}
B
Ben Adams 已提交
963

M
Mr.doob 已提交
964
						} else {
B
Ben Adams 已提交
965

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

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

M
Mr.doob 已提交
970
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
971
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
B
Ben Adams 已提交
972

M
Mr.doob 已提交
973
					} else {
B
Ben Adams 已提交
974

A
aardgoose 已提交
975
						if ( geometryAttribute.isInstancedBufferAttribute ) {
B
Ben Adams 已提交
976

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

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

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

M
Mr.doob 已提交
983
							}
B
Ben Adams 已提交
984

M
Mr.doob 已提交
985 986 987 988
						} else {

							state.enableAttribute( programAttribute );

M
Mr.doob 已提交
989
						}
B
Ben Adams 已提交
990

M
Mr.doob 已提交
991
						_gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
992
						_gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
M
Mr.doob 已提交
993

B
Ben Adams 已提交
994
					}
M
Mr.doob 已提交
995

996 997
				} else if ( materialDefaultAttributeValues !== undefined ) {

T
tschw 已提交
998
					var value = materialDefaultAttributeValues[ name ];
999

1000
					if ( value !== undefined ) {
M
Mr.doob 已提交
1001

1002
						switch ( value.length ) {
M
Mr.doob 已提交
1003

1004 1005 1006
							case 2:
								_gl.vertexAttrib2fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1007

1008 1009 1010
							case 3:
								_gl.vertexAttrib3fv( programAttribute, value );
								break;
M
Mr.doob 已提交
1011

1012 1013 1014
							case 4:
								_gl.vertexAttrib4fv( programAttribute, value );
								break;
1015

1016 1017
							default:
								_gl.vertexAttrib1fv( programAttribute, value );
1018 1019

						}
M
Mr.doob 已提交
1020 1021 1022 1023 1024 1025 1026 1027

					}

				}

			}

		}
1028

1029
		state.disableUnusedAttributes();
1030

M
Mr.doob 已提交
1031 1032
	}

M
Mr.doob 已提交
1033 1034
	// Sorting

1035
	function absNumericalSort( a, b ) {
1036

1037
		return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
1038 1039 1040

	}

M
Mr.doob 已提交
1041
	function painterSortStable( a, b ) {
M
Mr.doob 已提交
1042

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

U
unconed 已提交
1045
			return a.object.renderOrder - b.object.renderOrder;
1046

1047 1048 1049 1050
		} else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {

			return a.material.program.id - b.material.program.id;

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

M
Mr.doob 已提交
1053
			return a.material.id - b.material.id;
1054 1055

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

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

		} else {

1061
			return a.id - b.id;
M
Mr.doob 已提交
1062 1063 1064

		}

1065
	}
M
Mr.doob 已提交
1066

M
Mr.doob 已提交
1067
	function reversePainterSortStable( a, b ) {
1068

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

U
unconed 已提交
1071
			return a.object.renderOrder - b.object.renderOrder;
1072 1073

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

M
Mr.doob 已提交
1075
			return b.z - a.z;
1076 1077 1078 1079 1080 1081 1082

		} else {

			return a.id - b.id;

		}

1083
	}
1084

M
Mr.doob 已提交
1085 1086 1087 1088
	// Rendering

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

1089
		if ( camera !== undefined && camera.isCamera !== true ) {
M
Mr.doob 已提交
1090

1091
			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
M
Mr.doob 已提交
1092 1093 1094 1095 1096 1097
			return;

		}

		// reset caching for this frame

1098
		_currentGeometryProgram = '';
1099
		_currentMaterialId = - 1;
1100
		_currentCamera = null;
M
Mr.doob 已提交
1101 1102 1103

		// update scene graph

1104
		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
M
Mr.doob 已提交
1105 1106 1107

		// update camera matrices and frustum

1108
		if ( camera.parent === null ) camera.updateMatrixWorld();
M
Mr.doob 已提交
1109 1110 1111 1112 1113 1114

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

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

M
Mr.doob 已提交
1115
		lights.length = 0;
1116

M
Mr.doob 已提交
1117 1118
		opaqueObjectsLastIndex = - 1;
		transparentObjectsLastIndex = - 1;
1119

M
Mr.doob 已提交
1120 1121 1122
		sprites.length = 0;
		lensFlares.length = 0;

T
tschw 已提交
1123
		_localClippingEnabled = this.localClippingEnabled;
M
Mr.doob 已提交
1124
		_clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
T
tschw 已提交
1125

M
Mr.doob 已提交
1126
		projectObject( scene, camera, _this.sortObjects );
M
Mr.doob 已提交
1127

1128 1129 1130
		opaqueObjects.length = opaqueObjectsLastIndex + 1;
		transparentObjects.length = transparentObjectsLastIndex + 1;

M
Mr.doob 已提交
1131
		if ( _this.sortObjects === true ) {
1132 1133 1134

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

1136 1137
		}

M
Mr.doob 已提交
1138
		//
M
Mr.doob 已提交
1139

T
tschw 已提交
1140
		if ( _clippingEnabled ) _clipping.beginShadows();
T
tschw 已提交
1141

1142 1143
		setupShadows( lights );

M
Mr.doob 已提交
1144
		shadowMap.render( scene, camera );
M
Mr.doob 已提交
1145

1146 1147
		setupLights( lights, camera );

T
tschw 已提交
1148
		if ( _clippingEnabled ) _clipping.endShadows();
T
tschw 已提交
1149

M
Mr.doob 已提交
1150 1151
		//

1152 1153 1154 1155
		_infoRender.calls = 0;
		_infoRender.vertices = 0;
		_infoRender.faces = 0;
		_infoRender.points = 0;
M
Mr.doob 已提交
1156

1157 1158 1159 1160 1161 1162
		if ( renderTarget === undefined ) {

			renderTarget = null;

		}

M
Mr.doob 已提交
1163 1164
		this.setRenderTarget( renderTarget );

M
Mr.doob 已提交
1165 1166 1167 1168 1169 1170
		//

		var background = scene.background;

		if ( background === null ) {

1171
			state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
M
Mr.doob 已提交
1172

T
Takahiro 已提交
1173
		} else if ( background && background.isColor ) {
1174

1175
			state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
1176
			forceClear = true;
1177 1178 1179 1180 1181 1182 1183 1184 1185

		}

		if ( this.autoClear || forceClear ) {

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

		}

T
Takahiro 已提交
1186
		if ( background && background.isCubeTexture ) {
M
Mr.doob 已提交
1187

M
Mr.doob 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			if ( backgroundBoxCamera === undefined ) {

				backgroundBoxCamera = new PerspectiveCamera();

				backgroundBoxMesh = new Mesh(
					new BoxBufferGeometry( 5, 5, 5 ),
					new ShaderMaterial( {
						uniforms: ShaderLib.cube.uniforms,
						vertexShader: ShaderLib.cube.vertexShader,
						fragmentShader: ShaderLib.cube.fragmentShader,
						side: BackSide,
						depthTest: false,
						depthWrite: false,
						fog: false
					} )
				);

			}

			backgroundBoxCamera.projectionMatrix.copy( camera.projectionMatrix );

			backgroundBoxCamera.matrixWorld.extractRotation( camera.matrixWorld );
			backgroundBoxCamera.matrixWorldInverse.getInverse( backgroundBoxCamera.matrixWorld );
M
Mr.doob 已提交
1211 1212 1213


			backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
M
Mr.doob 已提交
1214
			backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundBoxCamera.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
M
Mr.doob 已提交
1215

1216 1217
			objects.update( backgroundBoxMesh );

M
Mr.doob 已提交
1218
			_this.renderBufferDirect( backgroundBoxCamera, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
M
Mr.doob 已提交
1219

T
Takahiro 已提交
1220
		} else if ( background && background.isTexture ) {
M
Mr.doob 已提交
1221

M
Mr.doob 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
			if ( backgroundPlaneCamera === undefined ) {

				backgroundPlaneCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );

				backgroundPlaneMesh = new Mesh(
					new PlaneBufferGeometry( 2, 2 ),
					new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
				);

			}

M
Mr.doob 已提交
1233 1234
			backgroundPlaneMesh.material.map = background;

1235 1236
			objects.update( backgroundPlaneMesh );

M
Mr.doob 已提交
1237
			_this.renderBufferDirect( backgroundPlaneCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
M
Mr.doob 已提交
1238

M
Mr.doob 已提交
1239 1240
		}

1241
		//
M
Mr.doob 已提交
1242 1243 1244

		if ( scene.overrideMaterial ) {

1245
			var overrideMaterial = scene.overrideMaterial;
M
Mr.doob 已提交
1246

1247 1248
			renderObjects( opaqueObjects, scene, camera, overrideMaterial );
			renderObjects( transparentObjects, scene, camera, overrideMaterial );
1249

M
Mr.doob 已提交
1250 1251 1252 1253
		} else {

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

R
Rich Harris 已提交
1254
			state.setBlending( NoBlending );
1255
			renderObjects( opaqueObjects, scene, camera );
M
Mr.doob 已提交
1256 1257 1258

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

1259
			renderObjects( transparentObjects, scene, camera );
M
Mr.doob 已提交
1260 1261 1262 1263 1264

		}

		// custom render plugins (post pass)

M
Mr.doob 已提交
1265
		spritePlugin.render( scene, camera );
1266
		lensFlarePlugin.render( scene, camera, _currentViewport );
M
Mr.doob 已提交
1267 1268 1269

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

M
Mr.doob 已提交
1270 1271
		if ( renderTarget ) {

1272
			textures.updateRenderTargetMipmap( renderTarget );
M
Mr.doob 已提交
1273 1274 1275

		}

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

M
Mr.doob 已提交
1278 1279
		state.setDepthTest( true );
		state.setDepthWrite( true );
1280
		state.setColorWrite( true );
M
Mr.doob 已提交
1281 1282 1283 1284

		// _gl.finish();

	};
M
Mr.doob 已提交
1285

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

1288
		var array, index;
M
Mr.doob 已提交
1289

1290
		// allocate the next position in the appropriate array
M
Mr.doob 已提交
1291 1292 1293

		if ( material.transparent ) {

1294 1295
			array = transparentObjects;
			index = ++ transparentObjectsLastIndex;
M
Mr.doob 已提交
1296 1297 1298

		} else {

1299 1300 1301 1302 1303
			array = opaqueObjects;
			index = ++ opaqueObjectsLastIndex;

		}

1304 1305
		// recycle existing render item or grow the array

1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
		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 已提交
1316 1317 1318

		} else {

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
			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 已提交
1330 1331 1332 1333 1334

		}

	}

M
Mr.doob 已提交
1335 1336
	// TODO Duplicated code (Frustum)

T
tschw 已提交
1337 1338 1339 1340 1341 1342 1343
	function isObjectViewable( object ) {

		var geometry = object.geometry;

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

M
Mr.doob 已提交
1344
		_sphere.copy( geometry.boundingSphere ).
1345
		applyMatrix4( object.matrixWorld );
M
Mr.doob 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361

		return isSphereViewable( _sphere );

	}

	function isSpriteViewable( sprite ) {

		_sphere.center.set( 0, 0, 0 );
		_sphere.radius = 0.7071067811865476;
		_sphere.applyMatrix4( sprite.matrixWorld );

		return isSphereViewable( _sphere );

	}

	function isSphereViewable( sphere ) {
T
tschw 已提交
1362 1363

		if ( ! _frustum.intersectsSphere( sphere ) ) return false;
T
tschw 已提交
1364 1365 1366 1367

		var numPlanes = _clipping.numPlanes;

		if ( numPlanes === 0 ) return true;
T
tschw 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

		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 已提交
1380
		} while ( ++ i !== numPlanes );
T
tschw 已提交
1381 1382 1383 1384 1385

		return true;

	}

M
Mr.doob 已提交
1386
	function projectObject( object, camera, sortObjects ) {
M
Mr.doob 已提交
1387

M
Mr.doob 已提交
1388
		if ( ! object.visible ) return;
M
Mr.doob 已提交
1389

M
Mr.doob 已提交
1390
		var visible = object.layers.test( camera.layers );
M
Mr.doob 已提交
1391

1392 1393 1394
		if ( visible ) {

			if ( object.isLight ) {
M
Mr.doob 已提交
1395

1396
				lights.push( object );
M
Mr.doob 已提交
1397

1398
			} else if ( object.isSprite ) {
M
Mr.doob 已提交
1399

M
Mr.doob 已提交
1400
				if ( ! object.frustumCulled || isSpriteViewable( object ) ) {
1401 1402 1403 1404

					sprites.push( object );

				}
M
Mr.doob 已提交
1405

1406
			} else if ( object.isLensFlare ) {
M
Mr.doob 已提交
1407

1408
				lensFlares.push( object );
M
Mr.doob 已提交
1409

1410
			} else if ( object.isImmediateRenderObject ) {
M
Mr.doob 已提交
1411

M
Mr.doob 已提交
1412
				if ( sortObjects ) {
M
Mr.doob 已提交
1413

M
Mr.doob 已提交
1414
					_vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
M
Mr.doob 已提交
1415

1416
				}
1417

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

1420
			} else if ( object.isMesh || object.isLine || object.isPoints ) {
M
Mr.doob 已提交
1421

1422
				if ( object.isSkinnedMesh ) {
M
Mr.doob 已提交
1423

1424
					object.skeleton.update();
1425

1426
				}
1427

M
Mr.doob 已提交
1428
				if ( ! object.frustumCulled || isObjectViewable( object ) ) {
1429

M
Mr.doob 已提交
1430
					if ( sortObjects ) {
1431

M
Mr.doob 已提交
1432
						_vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
1433

M
Mr.doob 已提交
1434
					}
1435

M
Mr.doob 已提交
1436 1437
					var geometry = objects.update( object );
					var material = object.material;
1438

M
Mr.doob 已提交
1439
					if ( Array.isArray( material ) ) {
1440

M
Mr.doob 已提交
1441
						var groups = geometry.groups;
1442

M
Mr.doob 已提交
1443
						for ( var i = 0, l = groups.length; i < l; i ++ ) {
1444

M
Mr.doob 已提交
1445 1446
							var group = groups[ i ];
							var groupMaterial = material[ group.materialIndex ];
M
Mr.doob 已提交
1447

M
Mr.doob 已提交
1448
							if ( groupMaterial && groupMaterial.visible ) {
1449

M
Mr.doob 已提交
1450
								pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
1451

M
Mr.doob 已提交
1452
							}
M
Mr.doob 已提交
1453

M
Mr.doob 已提交
1454
						}
M
Mr.doob 已提交
1455

M
Mr.doob 已提交
1456
					} else if ( material.visible ) {
1457

M
Mr.doob 已提交
1458
						pushRenderItem( object, geometry, material, _vector3.z, null );
O
OpenShift guest 已提交
1459

1460
					}
M
Mr.doob 已提交
1461

1462
				}
M
Mr.doob 已提交
1463

1464
			}
M
Mr.doob 已提交
1465

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

M
Mr.doob 已提交
1468
		var children = object.children;
M
Mr.doob 已提交
1469

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

M
Mr.doob 已提交
1472
			projectObject( children[ i ], camera, sortObjects );
M
Mr.doob 已提交
1473

1474
		}
1475

1476
	}
M
Mr.doob 已提交
1477

1478
	function renderObjects( renderList, scene, camera, overrideMaterial ) {
M
Mr.doob 已提交
1479

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

1482
			var renderItem = renderList[ i ];
M
Mr.doob 已提交
1483

1484
			var object = renderItem.object;
M
Mr.doob 已提交
1485 1486 1487
			var geometry = renderItem.geometry;
			var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
			var group = renderItem.group;
M
Mr.doob 已提交
1488

1489 1490
			object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
			object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
M
Mr.doob 已提交
1491

1492
			object.onBeforeRender( _this, scene, camera, geometry, material, group );
1493

1494
			if ( object.isImmediateRenderObject ) {
M
Mr.doob 已提交
1495

M
Mr.doob 已提交
1496
				setMaterial( material );
M
Mr.doob 已提交
1497

1498
				var program = setProgram( camera, scene.fog, material, object );
M
Mr.doob 已提交
1499

M
Mr.doob 已提交
1500
				_currentGeometryProgram = '';
M
Mr.doob 已提交
1501

M
Mr.doob 已提交
1502
				renderObjectImmediate( object, program, material );
1503

M
Mr.doob 已提交
1504
			} else {
M
Mr.doob 已提交
1505

1506
				_this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
M
Mr.doob 已提交
1507

M
Mr.doob 已提交
1508
			}
M
Mr.doob 已提交
1509

1510
			object.onAfterRender( _this, scene, camera, geometry, material, group );
D
Dusan Bosnjak 已提交
1511 1512


1513
		}
M
Mr.doob 已提交
1514

1515
	}
G
gero3 已提交
1516

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

1519
		var materialProperties = properties.get( material );
G
gero3 已提交
1520

T
tschw 已提交
1521
		var parameters = programCache.getParameters(
1522
			material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
T
tschw 已提交
1523

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

1526
		var program = materialProperties.program;
T
tschw 已提交
1527
		var programChange = true;
1528

1529
		if ( program === undefined ) {
B
Ben Adams 已提交
1530

M
Mr.doob 已提交
1531 1532
			// new material
			material.addEventListener( 'dispose', onMaterialDispose );
B
Ben Adams 已提交
1533

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

M
Mr.doob 已提交
1536
			// changed glsl or parameters
1537
			releaseMaterialProgramReference( material );
B
Ben Adams 已提交
1538

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

T
tschw 已提交
1541
			// same glsl and uniform list
T
tschw 已提交
1542 1543
			return;

T
tschw 已提交
1544
		} else {
B
Ben Adams 已提交
1545

T
tschw 已提交
1546 1547
			// only rebuild uniform list
			programChange = false;
B
Ben Adams 已提交
1548 1549 1550

		}

1551
		if ( programChange ) {
B
Ben Adams 已提交
1552

1553
			if ( parameters.shaderID ) {
B
Ben Adams 已提交
1554

R
Rich Harris 已提交
1555
				var shader = ShaderLib[ parameters.shaderID ];
B
Ben Adams 已提交
1556

1557 1558
				materialProperties.__webglShader = {
					name: material.type,
1559
					uniforms: UniformsUtils.clone( shader.uniforms ),
1560 1561 1562
					vertexShader: shader.vertexShader,
					fragmentShader: shader.fragmentShader
				};
B
Ben Adams 已提交
1563

1564
			} else {
B
Ben Adams 已提交
1565

1566 1567 1568 1569 1570 1571
				materialProperties.__webglShader = {
					name: material.type,
					uniforms: material.uniforms,
					vertexShader: material.vertexShader,
					fragmentShader: material.fragmentShader
				};
G
gero3 已提交
1572

1573
			}
G
gero3 已提交
1574

1575
			material.__webglShader = materialProperties.__webglShader;
G
gero3 已提交
1576

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

1579 1580
			materialProperties.program = program;
			material.program = program;
1581 1582 1583

		}

1584
		var programAttributes = program.getAttributes();
M
Mr.doob 已提交
1585 1586 1587 1588 1589

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

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

1592
				if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
M
Mr.doob 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

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

1608
				if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
M
Mr.doob 已提交
1609 1610 1611 1612 1613 1614 1615 1616 1617

					material.numSupportedMorphNormals ++;

				}

			}

		}

T
tschw 已提交
1618 1619
		var uniforms = materialProperties.__webglShader.uniforms;

1620
		if ( ! material.isShaderMaterial &&
1621 1622
			! material.isRawShaderMaterial ||
			material.clipping === true ) {
T
tschw 已提交
1623

T
tschw 已提交
1624
			materialProperties.numClippingPlanes = _clipping.numPlanes;
1625
			materialProperties.numIntersection = _clipping.numIntersection;
T
tschw 已提交
1626
			uniforms.clippingPlanes = _clipping.uniform;
T
tschw 已提交
1627 1628 1629

		}

1630
		materialProperties.fog = fog;
1631

1632
		// store the light setup it was created for
1633

1634
		materialProperties.lightsHash = _lights.hash;
1635

M
Mr.doob 已提交
1636
		if ( material.lights ) {
1637 1638 1639 1640 1641 1642

			// 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;
1643
			uniforms.rectAreaLights.value = _lights.rectArea;
M
Mr.doob 已提交
1644
			uniforms.pointLights.value = _lights.point;
1645 1646
			uniforms.hemisphereLights.value = _lights.hemi;

1647 1648 1649 1650 1651 1652
			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;
1653
			// TODO (abelnation): add area lights shadow info to uniforms
1654

1655 1656
		}

T
tschw 已提交
1657 1658
		var progUniforms = materialProperties.program.getUniforms(),
			uniformsList =
1659
				WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
A
arose 已提交
1660

T
tschw 已提交
1661
		materialProperties.uniformsList = uniformsList;
A
arose 已提交
1662

M
Mr.doob 已提交
1663
	}
M
Mr.doob 已提交
1664

1665 1666
	function setMaterial( material ) {

M
Mr.doob 已提交
1667 1668 1669
		material.side === DoubleSide
			? state.disable( _gl.CULL_FACE )
			: state.enable( _gl.CULL_FACE );
T
tschw 已提交
1670

R
Rich Harris 已提交
1671
		state.setFlipSided( material.side === BackSide );
M
Mr.doob 已提交
1672

M
Mr.doob 已提交
1673 1674 1675
		material.transparent === true
			? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
			: state.setBlending( NoBlending );
1676

B
Ben Adams 已提交
1677
		state.setDepthFunc( material.depthFunc );
M
Mr.doob 已提交
1678 1679
		state.setDepthTest( material.depthTest );
		state.setDepthWrite( material.depthWrite );
1680
		state.setColorWrite( material.colorWrite );
M
Mr.doob 已提交
1681
		state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
1682 1683 1684

	}

1685
	function setProgram( camera, fog, material, object ) {
M
Mr.doob 已提交
1686 1687 1688

		_usedTextureUnits = 0;

1689
		var materialProperties = properties.get( material );
1690

T
tschw 已提交
1691 1692 1693 1694 1695
		if ( _clippingEnabled ) {

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

				var useCache =
1696 1697
					camera === _currentCamera &&
					material.id === _currentMaterialId;
T
tschw 已提交
1698 1699 1700 1701

				// we might want to call this function with some ClippingGroup
				// object instead of the material, once it becomes feasible
				// (#8465, #8379)
T
tschw 已提交
1702
				_clipping.setState(
1703 1704
					material.clippingPlanes, material.clipIntersection, material.clipShadows,
					camera, materialProperties, useCache );
T
tschw 已提交
1705 1706 1707 1708 1709

			}

		}

1710
		if ( material.needsUpdate === false ) {
1711

1712
			if ( materialProperties.program === undefined ) {
1713

1714
				material.needsUpdate = true;
1715

1716
			} else if ( material.fog && materialProperties.fog !== fog ) {
1717

M
Mr.doob 已提交
1718
				material.needsUpdate = true;
1719

1720
			} else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
1721

1722
				material.needsUpdate = true;
1723

1724
			} else if ( materialProperties.numClippingPlanes !== undefined &&
1725
				( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
M
Mr.doob 已提交
1726
				materialProperties.numIntersection !== _clipping.numIntersection ) ) {
1727 1728 1729

				material.needsUpdate = true;

1730
			}
1731 1732 1733 1734

		}

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

1736
			initMaterial( material, fog, object );
M
Mr.doob 已提交
1737 1738 1739 1740
			material.needsUpdate = false;

		}

1741
		var refreshProgram = false;
M
Mr.doob 已提交
1742
		var refreshMaterial = false;
1743
		var refreshLights = false;
M
Mr.doob 已提交
1744

1745
		var program = materialProperties.program,
1746
			p_uniforms = program.getUniforms(),
1747
			m_uniforms = materialProperties.__webglShader.uniforms;
M
Mr.doob 已提交
1748

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

1751 1752
			_gl.useProgram( program.program );
			_currentProgram = program.id;
M
Mr.doob 已提交
1753

1754
			refreshProgram = true;
M
Mr.doob 已提交
1755
			refreshMaterial = true;
1756
			refreshLights = true;
M
Mr.doob 已提交
1757 1758 1759 1760 1761 1762

		}

		if ( material.id !== _currentMaterialId ) {

			_currentMaterialId = material.id;
1763

M
Mr.doob 已提交
1764 1765 1766 1767
			refreshMaterial = true;

		}

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

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

G
gero3 已提交
1772
			if ( capabilities.logarithmicDepthBuffer ) {
1773

T
tschw 已提交
1774
				p_uniforms.setValue( _gl, 'logDepthBufFC',
1775
					2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
1776 1777 1778 1779

			}


1780 1781 1782 1783 1784 1785 1786 1787 1788
			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 已提交
1789
				refreshLights = true;		// remains set until update done
1790 1791

			}
M
Mr.doob 已提交
1792

1793 1794 1795
			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

1796
			if ( material.isShaderMaterial ||
1797 1798 1799
				material.isMeshPhongMaterial ||
				material.isMeshStandardMaterial ||
				material.envMap ) {
1800

T
tschw 已提交
1801 1802 1803
				var uCamPos = p_uniforms.map.cameraPosition;

				if ( uCamPos !== undefined ) {
1804

T
tschw 已提交
1805
					uCamPos.setValue( _gl,
1806
						_vector3.setFromMatrixPosition( camera.matrixWorld ) );
1807 1808 1809 1810 1811

				}

			}

1812
			if ( material.isMeshPhongMaterial ||
1813 1814 1815 1816
				material.isMeshLambertMaterial ||
				material.isMeshBasicMaterial ||
				material.isMeshStandardMaterial ||
				material.isShaderMaterial ||
1817
				object.isSkinnedMesh ) {
1818

T
tschw 已提交
1819
				p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
1820 1821 1822

			}

T
tschw 已提交
1823 1824
			p_uniforms.set( _gl, _this, 'toneMappingExposure' );
			p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
M
Mr.doob 已提交
1825

M
Mr.doob 已提交
1826 1827 1828 1829 1830 1831
		}

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

1832
		if ( object.isSkinnedMesh ) {
M
Mr.doob 已提交
1833

T
tschw 已提交
1834 1835
			p_uniforms.setOptional( _gl, object, 'bindMatrix' );
			p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
1836

T
tschw 已提交
1837
			var skeleton = object.skeleton;
1838

T
tschw 已提交
1839
			if ( skeleton ) {
1840

1841
				if ( capabilities.floatVertexTextures ) {
M
Mr.doob 已提交
1842

T
tschw 已提交
1843
					p_uniforms.set( _gl, skeleton, 'boneTexture' );
1844
					p_uniforms.set( _gl, skeleton, 'boneTextureSize' );
M
Mr.doob 已提交
1845

T
tschw 已提交
1846
				} else {
M
Mr.doob 已提交
1847

T
tschw 已提交
1848
					p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
M
Mr.doob 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857

				}

			}

		}

		if ( refreshMaterial ) {

M
Mr.doob 已提交
1858
			if ( material.lights ) {
M
Mr.doob 已提交
1859

1860
				// the current material requires lighting info
M
Mr.doob 已提交
1861

T
tschw 已提交
1862 1863 1864 1865 1866 1867
				// 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 已提交
1868

T
tschw 已提交
1869
				markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
G
gero3 已提交
1870

T
tschw 已提交
1871
			}
G
gero3 已提交
1872

T
tschw 已提交
1873
			// refresh uniforms common to several materials
G
gero3 已提交
1874

T
tschw 已提交
1875
			if ( fog && material.fog ) {
G
gero3 已提交
1876

T
tschw 已提交
1877
				refreshUniformsFog( m_uniforms, fog );
M
Mr.doob 已提交
1878 1879 1880

			}

1881
			if ( material.isMeshBasicMaterial ||
1882 1883 1884
				material.isMeshLambertMaterial ||
				material.isMeshPhongMaterial ||
				material.isMeshStandardMaterial ||
1885
				material.isMeshNormalMaterial ||
1886
				material.isMeshDepthMaterial ) {
M
Mr.doob 已提交
1887 1888 1889 1890 1891 1892 1893

				refreshUniformsCommon( m_uniforms, material );

			}

			// refresh single material specific uniforms

1894
			if ( material.isLineBasicMaterial ) {
M
Mr.doob 已提交
1895 1896 1897

				refreshUniformsLine( m_uniforms, material );

1898
			} else if ( material.isLineDashedMaterial ) {
M
Mr.doob 已提交
1899 1900 1901 1902

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

1903
			} else if ( material.isPointsMaterial ) {
M
Mr.doob 已提交
1904

M
Mr.doob 已提交
1905
				refreshUniformsPoints( m_uniforms, material );
M
Mr.doob 已提交
1906

1907
			} else if ( material.isMeshLambertMaterial ) {
1908 1909 1910

				refreshUniformsLambert( m_uniforms, material );

T
Takahiro 已提交
1911 1912 1913 1914
			} else if ( material.isMeshToonMaterial ) {

				refreshUniformsToon( m_uniforms, material );

1915 1916 1917 1918
			} else if ( material.isMeshPhongMaterial ) {

				refreshUniformsPhong( m_uniforms, material );

1919
			} else if ( material.isMeshPhysicalMaterial ) {
W
WestLangley 已提交
1920 1921 1922

				refreshUniformsPhysical( m_uniforms, material );

1923
			} else if ( material.isMeshStandardMaterial ) {
W
WestLangley 已提交
1924

1925
				refreshUniformsStandard( m_uniforms, material );
W
WestLangley 已提交
1926

1927
			} else if ( material.isMeshDepthMaterial ) {
M
Mr.doob 已提交
1928

1929 1930 1931 1932 1933 1934 1935 1936
				if ( material.displacementMap ) {

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

				}

1937
			} else if ( material.isMeshNormalMaterial ) {
M
Mr.doob 已提交
1938

1939
				refreshUniformsNormal( m_uniforms, material );
M
Mr.doob 已提交
1940 1941 1942

			}

M
Mr.doob 已提交
1943 1944 1945 1946 1947 1948
			// RectAreaLight Texture
			// TODO (mrdoob): Find a nicer implementation

			if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
			if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;

R
Rich Harris 已提交
1949
			WebGLUniforms.upload(
1950
				_gl, materialProperties.uniformsList, m_uniforms, _this );
A
arose 已提交
1951 1952 1953

		}

M
Mr.doob 已提交
1954

T
tschw 已提交
1955
		// common matrices
M
Mr.doob 已提交
1956

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

T
tschw 已提交
1961
		return program;
A
arose 已提交
1962 1963 1964

	}

M
Mr.doob 已提交
1965 1966
	// Uniforms (refresh uniforms objects)

M
Mr.doob 已提交
1967
	function refreshUniformsCommon( uniforms, material ) {
M
Mr.doob 已提交
1968 1969 1970

		uniforms.opacity.value = material.opacity;

1971
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
1972

1973
		if ( material.emissive ) {
M
Mr.doob 已提交
1974

1975
			uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
M
Mr.doob 已提交
1976 1977 1978

		}

1979 1980 1981
		uniforms.map.value = material.map;
		uniforms.specularMap.value = material.specularMap;
		uniforms.alphaMap.value = material.alphaMap;
M
Mr.doob 已提交
1982

1983 1984 1985 1986 1987 1988 1989
		if ( material.lightMap ) {

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

		}

1990
		if ( material.aoMap ) {
1991

1992 1993
			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;
1994 1995 1996

		}

M
Mr.doob 已提交
1997
		// uv repeat and offset setting priorities
M
Mr.doob 已提交
1998 1999 2000 2001 2002
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
2003
		// 6. emissive map
M
Mr.doob 已提交
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014

		var uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

2015 2016 2017 2018
		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

M
Mr.doob 已提交
2019 2020 2021 2022 2023 2024 2025 2026
		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

2027 2028 2029 2030 2031 2032 2033 2034
		} else if ( material.roughnessMap ) {

			uvScaleMap = material.roughnessMap;

		} else if ( material.metalnessMap ) {

			uvScaleMap = material.metalnessMap;

2035 2036 2037 2038
		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

2039 2040 2041 2042
		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

M
Mr.doob 已提交
2043 2044 2045 2046
		}

		if ( uvScaleMap !== undefined ) {

2047
			// backwards compatibility
2048
			if ( uvScaleMap.isWebGLRenderTarget ) {
M
Mr.doob 已提交
2049 2050 2051 2052 2053

				uvScaleMap = uvScaleMap.texture;

			}

M
Mr.doob 已提交
2054 2055 2056 2057 2058 2059 2060 2061
			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;
2062 2063 2064 2065 2066

		// 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
T
Takahiro 已提交
2067
		uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
M
Mr.doob 已提交
2068

2069
		uniforms.reflectivity.value = material.reflectivity;
M
Mr.doob 已提交
2070 2071
		uniforms.refractionRatio.value = material.refractionRatio;

M
Mr.doob 已提交
2072
	}
M
Mr.doob 已提交
2073

M
Mr.doob 已提交
2074
	function refreshUniformsLine( uniforms, material ) {
M
Mr.doob 已提交
2075 2076 2077 2078

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

M
Mr.doob 已提交
2079
	}
M
Mr.doob 已提交
2080

M
Mr.doob 已提交
2081
	function refreshUniformsDash( uniforms, material ) {
M
Mr.doob 已提交
2082 2083 2084 2085 2086

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

M
Mr.doob 已提交
2087
	}
M
Mr.doob 已提交
2088

M
Mr.doob 已提交
2089
	function refreshUniformsPoints( uniforms, material ) {
M
Mr.doob 已提交
2090

2091
		uniforms.diffuse.value = material.color;
M
Mr.doob 已提交
2092
		uniforms.opacity.value = material.opacity;
2093
		uniforms.size.value = material.size * _pixelRatio;
2094
		uniforms.scale.value = _height * 0.5;
M
Mr.doob 已提交
2095 2096 2097

		uniforms.map.value = material.map;

2098 2099 2100 2101 2102 2103 2104 2105 2106
		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 已提交
2107
	}
M
Mr.doob 已提交
2108

M
Mr.doob 已提交
2109
	function refreshUniformsFog( uniforms, fog ) {
M
Mr.doob 已提交
2110 2111 2112

		uniforms.fogColor.value = fog.color;

2113
		if ( fog.isFog ) {
M
Mr.doob 已提交
2114 2115 2116 2117

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

2118
		} else if ( fog.isFogExp2 ) {
M
Mr.doob 已提交
2119 2120 2121 2122 2123

			uniforms.fogDensity.value = fog.density;

		}

M
Mr.doob 已提交
2124
	}
M
Mr.doob 已提交
2125

M
Mr.doob 已提交
2126
	function refreshUniformsLambert( uniforms, material ) {
2127 2128 2129 2130 2131 2132 2133 2134 2135

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

	}

M
Mr.doob 已提交
2136
	function refreshUniformsPhong( uniforms, material ) {
M
Mr.doob 已提交
2137

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

2141
		if ( material.emissiveMap ) {
2142

2143
			uniforms.emissiveMap.value = material.emissiveMap;
2144

2145
		}
M
Mr.doob 已提交
2146

2147 2148 2149 2150
		if ( material.bumpMap ) {

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

2152
		}
M
Mr.doob 已提交
2153

2154 2155 2156 2157 2158 2159
		if ( material.normalMap ) {

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

		}
M
Mr.doob 已提交
2160

2161 2162 2163 2164 2165
		if ( material.displacementMap ) {

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

2167
		}
2168

T
Takahiro 已提交
2169 2170 2171 2172 2173 2174
	}

	function refreshUniformsToon( uniforms, material ) {

		refreshUniformsPhong( uniforms, material );

T
Takahiro 已提交
2175
		if ( material.gradientMap ) {
T
Takahiro 已提交
2176

T
Takahiro 已提交
2177
			uniforms.gradientMap.value = material.gradientMap;
T
Takahiro 已提交
2178 2179 2180

		}

2181 2182
	}

M
Mr.doob 已提交
2183
	function refreshUniformsStandard( uniforms, material ) {
W
WestLangley 已提交
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 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

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

		}

	}

M
Mr.doob 已提交
2237
	function refreshUniformsPhysical( uniforms, material ) {
W
WestLangley 已提交
2238

2239 2240 2241
		uniforms.clearCoat.value = material.clearCoat;
		uniforms.clearCoatRoughness.value = material.clearCoatRoughness;

W
WestLangley 已提交
2242 2243 2244 2245
		refreshUniformsStandard( uniforms, material );

	}

2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
	function refreshUniformsNormal( uniforms, material ) {

		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;

		}

	}

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

M
Mr.doob 已提交
2274
	function markUniformsLightsNeedsUpdate( uniforms, value ) {
2275

M
Mr.doob 已提交
2276
		uniforms.ambientLightColor.needsUpdate = value;
2277

B
Ben Houston 已提交
2278 2279 2280
		uniforms.directionalLights.needsUpdate = value;
		uniforms.pointLights.needsUpdate = value;
		uniforms.spotLights.needsUpdate = value;
2281
		uniforms.rectAreaLights.needsUpdate = value;
B
Ben Houston 已提交
2282
		uniforms.hemisphereLights.needsUpdate = value;
2283

M
Mr.doob 已提交
2284
	}
2285

T
tschw 已提交
2286
	// Lighting
M
Mr.doob 已提交
2287

M
Mr.doob 已提交
2288
	function setupShadows( lights ) {
2289 2290 2291 2292 2293 2294 2295 2296 2297

		var lightShadowsLength = 0;

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

			var light = lights[ i ];

			if ( light.castShadow ) {

M
Mr.doob 已提交
2298 2299
				_lights.shadows[ lightShadowsLength ] = light;
				lightShadowsLength ++;
2300 2301 2302 2303 2304 2305 2306 2307 2308

			}

		}

		_lights.shadows.length = lightShadowsLength;

	}

M
Mr.doob 已提交
2309
	function setupLights( lights, camera ) {
M
Mr.doob 已提交
2310

B
brason 已提交
2311
		var l, ll, light,
2312 2313 2314 2315 2316
			r = 0, g = 0, b = 0,
			color,
			intensity,
			distance,
			shadowMap,
M
Mr.doob 已提交
2317

2318
			viewMatrix = camera.matrixWorldInverse,
M
Mr.doob 已提交
2319

M
Mr.doob 已提交
2320 2321 2322 2323 2324
			directionalLength = 0,
			pointLength = 0,
			spotLength = 0,
			rectAreaLength = 0,
			hemiLength = 0;
M
Mr.doob 已提交
2325 2326 2327 2328 2329 2330 2331 2332 2333

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

			light = lights[ l ];

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

2334
			shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
2335

2336
			if ( light.isAmbientLight ) {
M
Mr.doob 已提交
2337

2338 2339 2340
				r += color.r * intensity;
				g += color.g * intensity;
				b += color.b * intensity;
M
Mr.doob 已提交
2341

2342
			} else if ( light.isDirectionalLight ) {
M
Mr.doob 已提交
2343

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

2346
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
M
Mr.doob 已提交
2347
				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
2348
				_vector3.setFromMatrixPosition( light.target.matrixWorld );
M
Mr.doob 已提交
2349 2350 2351
				uniforms.direction.sub( _vector3 );
				uniforms.direction.transformDirection( viewMatrix );

2352
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2353

2354
				if ( light.castShadow ) {
M
Mr.doob 已提交
2355

2356 2357 2358
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2359

2360 2361
				}

2362
				_lights.directionalShadowMap[ directionalLength ] = shadowMap;
2363
				_lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
2364
				_lights.directional[ directionalLength ++ ] = uniforms;
M
Mr.doob 已提交
2365

2366
			} else if ( light.isSpotLight ) {
M
Mr.doob 已提交
2367

M
Mr.doob 已提交
2368
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2369 2370 2371

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

M
Mr.doob 已提交
2373 2374 2375 2376 2377 2378 2379 2380
				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 );

2381 2382
				uniforms.coneCos = Math.cos( light.angle );
				uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
M
Mr.doob 已提交
2383
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
M
Mr.doob 已提交
2384

2385
				uniforms.shadow = light.castShadow;
M
Mr.doob 已提交
2386

2387 2388
				if ( light.castShadow ) {

2389 2390 2391
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;
2392

2393 2394
				}

2395
				_lights.spotShadowMap[ spotLength ] = shadowMap;
2396
				_lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
M
Mr.doob 已提交
2397
				_lights.spot[ spotLength ++ ] = uniforms;
2398

2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
			} else if ( light.isRectAreaLight ) {

				var uniforms = lightCache.get( light );

				// (a) intensity controls irradiance of entire light
				uniforms.color
					.copy( color )
					.multiplyScalar( intensity / ( light.width * light.height ) );

				// (b) intensity controls the radiance per light area
				// uniforms.color.copy( color ).multiplyScalar( intensity );

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );

				// extract local rotation of light to derive width/height half vectors
				_matrix42.identity();
				_matrix4.copy( light.matrixWorld );
				_matrix4.premultiply( viewMatrix );
				_matrix42.extractRotation( _matrix4 );

				uniforms.halfWidth.set( light.width * 0.5,                0.0, 0.0 );
				uniforms.halfHeight.set(              0.0, light.height * 0.5, 0.0 );

				uniforms.halfWidth.applyMatrix4( _matrix42 );
				uniforms.halfHeight.applyMatrix4( _matrix42 );

				// TODO (abelnation): RectAreaLight distance?
				// uniforms.distance = distance;

				_lights.rectArea[ rectAreaLength ++ ] = uniforms;

2431
			} else if ( light.isPointLight ) {
M
Mr.doob 已提交
2432

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

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

M
Mr.doob 已提交
2438 2439
				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				uniforms.distance = light.distance;
M
Mr.doob 已提交
2440 2441
				uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;

2442
				uniforms.shadow = light.castShadow;
2443

M
Mr.doob 已提交
2444
				if ( light.castShadow ) {
2445

2446 2447 2448 2449 2450
					uniforms.shadowBias = light.shadow.bias;
					uniforms.shadowRadius = light.shadow.radius;
					uniforms.shadowMapSize = light.shadow.mapSize;

				}
2451

2452
				_lights.pointShadowMap[ pointLength ] = shadowMap;
2453

2454 2455
				if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {

R
Rich Harris 已提交
2456
					_lights.pointShadowMatrix[ pointLength ] = new Matrix4();
2457

2458 2459
				}

2460 2461 2462 2463 2464
				// 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 已提交
2465
				_lights.point[ pointLength ++ ] = uniforms;
2466

2467
			} else if ( light.isHemisphereLight ) {
M
Mr.doob 已提交
2468

M
Mr.doob 已提交
2469
				var uniforms = lightCache.get( light );
M
Mr.doob 已提交
2470 2471 2472 2473

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

M
Mr.doob 已提交
2475 2476
				uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
				uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
M
Mr.doob 已提交
2477

M
Mr.doob 已提交
2478
				_lights.hemi[ hemiLength ++ ] = uniforms;
M
Mr.doob 已提交
2479 2480 2481 2482 2483

			}

		}

M
Mr.doob 已提交
2484 2485 2486
		_lights.ambient[ 0 ] = r;
		_lights.ambient[ 1 ] = g;
		_lights.ambient[ 2 ] = b;
M
Mr.doob 已提交
2487

M
Mr.doob 已提交
2488 2489
		_lights.directional.length = directionalLength;
		_lights.spot.length = spotLength;
2490
		_lights.rectArea.length = rectAreaLength;
2491
		_lights.point.length = pointLength;
M
Mr.doob 已提交
2492
		_lights.hemi.length = hemiLength;
2493

2494 2495
		// TODO (sam-g-steel) why aren't we using join
		_lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
2496

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

	// GL state setting

	this.setFaceCulling = function ( cullFace, frontFaceDirection ) {

T
tschw 已提交
2503
		state.setCullFace( cullFace );
R
Rich Harris 已提交
2504
		state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
M
Mr.doob 已提交
2505 2506 2507 2508 2509

	};

	// Textures

T
tschw 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
	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;

	}

2526
	this.allocTextureUnit = allocTextureUnit;
T
tschw 已提交
2527

2528
	// this.setTexture2D = setTexture2D;
M
Mr.doob 已提交
2529
	this.setTexture2D = ( function () {
T
tschw 已提交
2530

2531
		var warned = false;
T
tschw 已提交
2532

2533
		// backwards compatibility: peel texture.texture
W
WestLangley 已提交
2534
		return function setTexture2D( texture, slot ) {
T
tschw 已提交
2535

T
Takahiro 已提交
2536
			if ( texture && texture.isWebGLRenderTarget ) {
T
tschw 已提交
2537

2538
				if ( ! warned ) {
T
tschw 已提交
2539

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

2543
				}
T
tschw 已提交
2544

2545
				texture = texture.texture;
T
tschw 已提交
2546

2547
			}
T
tschw 已提交
2548

2549
			textures.setTexture2D( texture, slot );
T
tschw 已提交
2550

2551
		};
T
tschw 已提交
2552

2553
	}() );
T
tschw 已提交
2554

M
Mr.doob 已提交
2555
	this.setTexture = ( function () {
2556 2557 2558

		var warned = false;

W
WestLangley 已提交
2559
		return function setTexture( texture, slot ) {
2560 2561 2562 2563 2564 2565 2566 2567

			if ( ! warned ) {

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

			}

2568
			textures.setTexture2D( texture, slot );
2569 2570 2571 2572 2573

		};

	}() );

M
Mr.doob 已提交
2574
	this.setTextureCube = ( function () {
2575 2576 2577

		var warned = false;

W
WestLangley 已提交
2578
		return function setTextureCube( texture, slot ) {
2579 2580

			// backwards compatibility: peel texture.texture
T
Takahiro 已提交
2581
			if ( texture && texture.isWebGLRenderTargetCube ) {
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595

				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
T
Takahiro 已提交
2596
			if ( ( texture && texture.isCubeTexture ) ||
2597
				( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
2598 2599 2600 2601

				// CompressedTexture can have Array in image :/

				// this function alone should take care of cube textures
2602
				textures.setTextureCube( texture, slot );
2603 2604 2605 2606 2607

			} else {

				// assumed: texture property of THREE.WebGLRenderTargetCube

2608
				textures.setTextureCubeDynamic( texture, slot );
2609 2610 2611 2612 2613 2614

			}

		};

	}() );
T
tschw 已提交
2615

M
Mr.doob 已提交
2616
	this.getCurrentRenderTarget = function () {
2617 2618 2619

		return _currentRenderTarget;

M
Michael Herzog 已提交
2620
	};
2621

2622
	this.setRenderTarget = function ( renderTarget ) {
M
Mr.doob 已提交
2623

2624 2625
		_currentRenderTarget = renderTarget;

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

2628
			textures.setupRenderTarget( renderTarget );
M
Mr.doob 已提交
2629 2630 2631

		}

T
Takahiro 已提交
2632
		var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
2633
		var framebuffer;
M
Mr.doob 已提交
2634 2635 2636

		if ( renderTarget ) {

2637
			var renderTargetProperties = properties.get( renderTarget );
F
Fordy 已提交
2638

M
Mr.doob 已提交
2639 2640
			if ( isCube ) {

2641
				framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
M
Mr.doob 已提交
2642 2643 2644

			} else {

2645
				framebuffer = renderTargetProperties.__webglFramebuffer;
M
Mr.doob 已提交
2646 2647 2648

			}

2649 2650
			_currentScissor.copy( renderTarget.scissor );
			_currentScissorTest = renderTarget.scissorTest;
2651

2652
			_currentViewport.copy( renderTarget.viewport );
M
Mr.doob 已提交
2653 2654 2655 2656 2657

		} else {

			framebuffer = null;

2658
			_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
2659
			_currentScissorTest = _scissorTest;
2660

2661
			_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
M
Mr.doob 已提交
2662 2663 2664

		}

M
Mr.doob 已提交
2665
		if ( _currentFramebuffer !== framebuffer ) {
M
Mr.doob 已提交
2666 2667 2668 2669 2670 2671

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

		}

2672 2673
		state.scissor( _currentScissor );
		state.setScissorTest( _currentScissorTest );
2674

2675
		state.viewport( _currentViewport );
2676

M
Mr.doob 已提交
2677 2678 2679
		if ( isCube ) {

			var textureProperties = properties.get( renderTarget.texture );
2680
			_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
M
Mr.doob 已提交
2681 2682 2683

		}

M
Mr.doob 已提交
2684 2685
	};

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

T
Takahiro 已提交
2688
		if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
2689

2690
			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
G
gero3 已提交
2691
			return;
2692

G
gero3 已提交
2693
		}
2694

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

M
Mr.doob 已提交
2697
		if ( framebuffer ) {
2698

G
gero3 已提交
2699
			var restore = false;
2700

M
Mr.doob 已提交
2701
			if ( framebuffer !== _currentFramebuffer ) {
2702

M
Mr.doob 已提交
2703
				_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
2704

G
gero3 已提交
2705
				restore = true;
2706

G
gero3 已提交
2707
			}
2708

M
Mr.doob 已提交
2709
			try {
2710

M
Mr.doob 已提交
2711
				var texture = renderTarget.texture;
M
Mr.doob 已提交
2712 2713
				var textureFormat = texture.format;
				var textureType = texture.type;
2714

M
Mr.doob 已提交
2715
				if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
2716

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

M
Mr.doob 已提交
2720
				}
2721

M
Mr.doob 已提交
2722
				if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
2723 2724
					! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
					! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
2725

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

M
Mr.doob 已提交
2729
				}
2730

M
Mr.doob 已提交
2731
				if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
2732

2733 2734
					// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)

2735
					if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
2736

M
Mr.doob 已提交
2737
						_gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
2738 2739

					}
2740

M
Mr.doob 已提交
2741
				} else {
M
Mr.doob 已提交
2742

M
Mr.doob 已提交
2743 2744 2745
					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

				}
M
Mr.doob 已提交
2746

M
Mr.doob 已提交
2747
			} finally {
M
Mr.doob 已提交
2748

M
Mr.doob 已提交
2749 2750 2751
				if ( restore ) {

					_gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
M
Mr.doob 已提交
2752

M
Mr.doob 已提交
2753 2754 2755
				}

			}
M
Mr.doob 已提交
2756 2757 2758

		}

M
Mr.doob 已提交
2759 2760
	};

M
Mr.doob 已提交
2761 2762
	// Map three.js constants to WebGL constants

M
Mr.doob 已提交
2763
	function paramThreeToGL( p ) {
M
Mr.doob 已提交
2764

2765 2766
		var extension;

R
Rich Harris 已提交
2767 2768 2769
		if ( p === RepeatWrapping ) return _gl.REPEAT;
		if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
		if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
M
Mr.doob 已提交
2770

R
Rich Harris 已提交
2771 2772 2773
		if ( p === NearestFilter ) return _gl.NEAREST;
		if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
		if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
M
Mr.doob 已提交
2774

R
Rich Harris 已提交
2775 2776 2777
		if ( p === LinearFilter ) return _gl.LINEAR;
		if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
		if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
M
Mr.doob 已提交
2778

R
Rich Harris 已提交
2779 2780 2781 2782
		if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
		if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
		if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
		if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
M
Mr.doob 已提交
2783

R
Rich Harris 已提交
2784 2785 2786 2787 2788 2789
		if ( p === ByteType ) return _gl.BYTE;
		if ( p === ShortType ) return _gl.SHORT;
		if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
		if ( p === IntType ) return _gl.INT;
		if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
		if ( p === FloatType ) return _gl.FLOAT;
M
Mr.doob 已提交
2790

2791
		if ( p === HalfFloatType ) {
2792

2793
			extension = extensions.get( 'OES_texture_half_float' );
2794

2795
			if ( extension !== null ) return extension.HALF_FLOAT_OES;
2796 2797 2798

		}

R
Rich Harris 已提交
2799 2800 2801 2802 2803 2804
		if ( p === AlphaFormat ) return _gl.ALPHA;
		if ( p === RGBFormat ) return _gl.RGB;
		if ( p === RGBAFormat ) return _gl.RGBA;
		if ( p === LuminanceFormat ) return _gl.LUMINANCE;
		if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
		if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
2805
		if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
M
Mr.doob 已提交
2806

R
Rich Harris 已提交
2807 2808 2809
		if ( p === AddEquation ) return _gl.FUNC_ADD;
		if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
		if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
M
Mr.doob 已提交
2810

R
Rich Harris 已提交
2811 2812 2813 2814 2815 2816 2817 2818
		if ( p === ZeroFactor ) return _gl.ZERO;
		if ( p === OneFactor ) return _gl.ONE;
		if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
		if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
		if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
		if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
		if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
		if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
M
Mr.doob 已提交
2819

R
Rich Harris 已提交
2820 2821 2822
		if ( p === DstColorFactor ) return _gl.DST_COLOR;
		if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
		if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
M
Mr.doob 已提交
2823

2824 2825
		if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
			p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
M
Mr.doob 已提交
2826

2827
			extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
2828

2829 2830 2831 2832 2833 2834 2835 2836
			if ( extension !== null ) {

				if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
				if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
				if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
				if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;

			}
M
Mr.doob 已提交
2837 2838 2839

		}

2840
		if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
2841
			p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
2842

2843
			extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
P
Pierre Lepers 已提交
2844

2845 2846 2847 2848 2849 2850 2851 2852
			if ( extension !== null ) {

				if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
				if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
				if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
				if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;

			}
P
Pierre Lepers 已提交
2853 2854 2855

		}

2856
		if ( p === RGB_ETC1_Format ) {
2857

2858
			extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
2859

2860
			if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
2861 2862 2863

		}

2864 2865 2866
		if ( p === MinEquation || p === MaxEquation ) {

			extension = extensions.get( 'EXT_blend_minmax' );
2867

2868
			if ( extension !== null ) {
2869

2870 2871 2872 2873
				if ( p === MinEquation ) return extension.MIN_EXT;
				if ( p === MaxEquation ) return extension.MAX_EXT;

			}
2874 2875 2876

		}

2877
		if ( p === UnsignedInt248Type ) {
2878

2879
			extension = extensions.get( 'WEBGL_depth_texture' );
2880

2881
			if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
2882 2883 2884

		}

M
Mr.doob 已提交
2885 2886
		return 0;

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

M
Mr.doob 已提交
2889
}
R
Rich Harris 已提交
2890

T
Tristan VALCKE 已提交
2891

2892
export { WebGLRenderer };