WebGLRenderer.js 37.4 KB
Newer Older
N
Nicolas Garcia Belmonte 已提交
1 2 3
/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
4
 * @author alteredq / http://alteredqualia.com/
N
Nicolas Garcia Belmonte 已提交
5 6
 */

7
THREE.WebGLRenderer = function ( scene ) {
M
Mr.doob 已提交
8

M
Mr.doob 已提交
9 10
	// Currently you can use just up to 4 directional / point lights total.
	// Chrome barfs on shader linking when there are more than 4 lights :(
M
Mr.doob 已提交
11

12
	// It seems problem comes from having too many varying vectors.
M
Mr.doob 已提交
13

14
	// Weirdly, this is not GPU limitation as the same shader works ok in Firefox.
M
Mr.doob 已提交
15
	// This difference could come from Chrome using ANGLE on Windows,
16
	// thus going DirectX9 route (while FF uses OpenGL).
M
Mr.doob 已提交
17

18 19
	var _canvas = document.createElement( 'canvas' ), _gl, _program,
	_modelViewMatrix = new THREE.Matrix4(), _normalMatrix,
M
Mr.doob 已提交
20

M
Mr.doob 已提交
21
	BASIC = 0, LAMBERT = 1, PHONG = 2, DEPTH = 3, NORMAL = 4, CUBE = 5, // material constants used in shader
M
Mr.doob 已提交
22

23
	maxLightCount = allocateLights( scene, 4 );
M
Mr.doob 已提交
24

N
Nicolas Garcia Belmonte 已提交
25 26 27 28
	this.domElement = _canvas;
	this.autoClear = true;

	initGL();
29
	initProgram( maxLightCount.directional, maxLightCount.point );
M
Mr.doob 已提交
30

31 32 33 34
	// Querying via gl.getParameter() reports different values for CH and FF for many max parameters.
	// On my GPU Chrome reports MAX_VARYING_VECTORS = 8, FF reports 0 yet compiles shaders with many
	// more varying vectors (up to 29 lights are ok, more start to throw warnings to FF error console
	// and then crash the browser).
M
Mr.doob 已提交
35

36
	//alert( dumpObject( getGLParams() ) );
M
Mr.doob 已提交
37 38


39 40 41 42
	function allocateLights( scene, maxLights ) {

		// heuristics to create shader parameters according to lights in the scene
		// (not to blow over maxLights budget)
M
Mr.doob 已提交
43

44 45 46
		if ( scene ) {

			var l, ll, light, dirLights = pointLights = maxDirLights = maxPointLights = 0;
M
Mr.doob 已提交
47

48
			for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {
M
Mr.doob 已提交
49

50
				light = scene.lights[ l ];
M
Mr.doob 已提交
51

52 53
				if ( light instanceof THREE.DirectionalLight ) dirLights++;
				if ( light instanceof THREE.PointLight ) pointLights++;
M
Mr.doob 已提交
54

55
			}
M
Mr.doob 已提交
56

57
			if ( ( pointLights + dirLights ) <= maxLights ) {
M
Mr.doob 已提交
58

59 60
				maxDirLights = dirLights;
				maxPointLights = pointLights;
M
Mr.doob 已提交
61

62
			} else {
M
Mr.doob 已提交
63

64 65
				maxDirLights = Math.ceil( maxLights * dirLights / ( pointLights + dirLights ) );
				maxPointLights = maxLights - maxDirLights;
M
Mr.doob 已提交
66

67
			}
M
Mr.doob 已提交
68

69
			return { 'directional' : maxDirLights, 'point' : maxPointLights };
M
Mr.doob 已提交
70

71
		}
M
Mr.doob 已提交
72

73
		return { 'directional' : 1, 'point' : maxLights - 1 };
M
Mr.doob 已提交
74

75
	};
N
Nicolas Garcia Belmonte 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

	this.setSize = function ( width, height ) {

		_canvas.width = width;
		_canvas.height = height;
		_gl.viewport( 0, 0, _canvas.width, _canvas.height );

	};

	this.clear = function () {

		_gl.clear( _gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT );

	};

91 92
	this.setupLights = function ( scene ) {

93
		var l, ll, light, r, g, b,
A
alteredq 已提交
94
			ambientLights = [], pointLights = [], directionalLights = [],
95
			colors = [], positions = [];
96

97
		_gl.uniform1i( _program.enableLighting, scene.lights.length );
98 99 100 101 102 103 104

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

			light = scene.lights[ l ];

			if ( light instanceof THREE.AmbientLight ) {

105
				ambientLights.push( light );
106

107
			} else if ( light instanceof THREE.DirectionalLight ) {
108

109
				directionalLights.push( light );
110

111 112
			} else if( light instanceof THREE.PointLight ) {

113
				pointLights.push( light );
M
Mr.doob 已提交
114

115 116 117
			}

		}
M
Mr.doob 已提交
118

119 120
		// sum all ambient lights
		r = g = b = 0.0;
M
Mr.doob 已提交
121

122
		for ( l = 0, ll = ambientLights.length; l < ll; l++ ) {
M
Mr.doob 已提交
123

124 125 126
			r += ambientLights[ l ].color.r;
			g += ambientLights[ l ].color.g;
			b += ambientLights[ l ].color.b;
M
Mr.doob 已提交
127

128
		}
M
Mr.doob 已提交
129

130 131 132
		_gl.uniform3f( _program.ambientLightColor, r, g, b );

		// pass directional lights as float arrays
M
Mr.doob 已提交
133

134
		colors = []; positions = [];
M
Mr.doob 已提交
135

136
		for ( l = 0, ll = directionalLights.length; l < ll; l++ ) {
M
Mr.doob 已提交
137

138
			light = directionalLights[ l ];
M
Mr.doob 已提交
139

140 141 142 143 144 145 146
			colors.push( light.color.r * light.intensity );
			colors.push( light.color.g * light.intensity );
			colors.push( light.color.b * light.intensity );

			positions.push( light.position.x );
			positions.push( light.position.y );
			positions.push( light.position.z );
M
Mr.doob 已提交
147

148
		}
M
Mr.doob 已提交
149

150 151 152 153 154
		if ( directionalLights.length ) {

			_gl.uniform1i(  _program.directionalLightNumber, directionalLights.length );
			_gl.uniform3fv( _program.directionalLightDirection, positions );
			_gl.uniform3fv( _program.directionalLightColor, colors );
M
Mr.doob 已提交
155

156
		}
157

158
		// pass point lights as float arrays
M
Mr.doob 已提交
159

160
		colors = []; positions = [];
M
Mr.doob 已提交
161

162
		for ( l = 0, ll = pointLights.length; l < ll; l++ ) {
M
Mr.doob 已提交
163

164
			light = pointLights[ l ];
M
Mr.doob 已提交
165

166 167 168 169 170 171 172
			colors.push( light.color.r * light.intensity );
			colors.push( light.color.g * light.intensity );
			colors.push( light.color.b * light.intensity );

			positions.push( light.position.x );
			positions.push( light.position.y );
			positions.push( light.position.z );
M
Mr.doob 已提交
173

174
		}
M
Mr.doob 已提交
175

176 177 178 179 180
		if ( pointLights.length ) {

			_gl.uniform1i(  _program.pointLightNumber, pointLights.length );
			_gl.uniform3fv( _program.pointLightPosition, positions );
			_gl.uniform3fv( _program.pointLightColor, colors );
M
Mr.doob 已提交
181

182
		}
M
Mr.doob 已提交
183

184 185 186 187
	};

	this.createBuffers = function ( object, mf ) {

188
		var f, fl, fi, face, vertexNormals, normal, uv, v1, v2, v3, v4, m, ml, i, l,
189 190 191 192 193 194 195 196 197 198

		materialFaceGroup = object.materialFaceGroup[ mf ],

		faceArray = [],
		lineArray = [],

		vertexArray = [],
		normalArray = [],
		uvArray = [],

199
		vertexIndex = 0,
200

201
		useSmoothNormals = false;
202

203 204 205
		// need to find out if there is any material in the object
		// (among all mesh materials and also face materials)
		// which would need smooth normals
206

207
		function needsSmoothNormals( material ) {
208

209
			return material && material.shading != undefined && material.shading == THREE.SmoothShading;
210

211
		}
212

213 214 215 216 217 218 219
		for ( m = 0, ml = object.material.length; m < ml; m++ ) {

			meshMaterial = object.material[ m ];

			if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {

				for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
M
Mr.doob 已提交
220

221
					if ( needsSmoothNormals( materialFaceGroup.material[ i ] ) ) {
M
Mr.doob 已提交
222

223 224
						useSmoothNormals = true;
						break;
M
Mr.doob 已提交
225

226 227 228 229 230 231 232
					}

				}

			} else {

				if ( needsSmoothNormals( meshMaterial ) ) {
M
Mr.doob 已提交
233

234 235
					useSmoothNormals = true;
					break;
M
Mr.doob 已提交
236

237 238 239
				}

			}
M
Mr.doob 已提交
240

241 242 243
			if ( useSmoothNormals ) break;

		}
M
Mr.doob 已提交
244

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
		for ( f = 0, fl = materialFaceGroup.faces.length; f < fl; f++ ) {

			fi = materialFaceGroup.faces[f];

			face = object.geometry.faces[ fi ];
			vertexNormals = face.vertexNormals;
			normal = face.normal;
			uv = object.geometry.uvs[ fi ];

			if ( face instanceof THREE.Face3 ) {

				v1 = object.geometry.vertices[ face.a ].position;
				v2 = object.geometry.vertices[ face.b ].position;
				v3 = object.geometry.vertices[ face.c ].position;

				vertexArray.push( v1.x, v1.y, v1.z );
				vertexArray.push( v2.x, v2.y, v2.z );
				vertexArray.push( v3.x, v3.y, v3.z );

264
				if ( vertexNormals.length == 3 && useSmoothNormals ) {
265

M
Mr.doob 已提交
266 267 268 269 270
					for ( i = 0; i < 3; i ++ ) {

						normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );

					}
271 272 273

				} else {

M
Mr.doob 已提交
274 275 276 277 278
					for ( i = 0; i < 3; i ++ ) {

						normalArray.push( normal.x, normal.y, normal.z );

					}
279 280 281 282 283

				}

				if ( uv ) {

M
Mr.doob 已提交
284 285 286 287
					for ( i = 0; i < 3; i ++ ) {

						uvArray.push( uv[ i ].u, uv[ i ].v );
					}
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

				}

				faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );

				// TODO: don't add lines that already exist (faces sharing edge)

				lineArray.push( vertexIndex, vertexIndex + 1 );
				lineArray.push( vertexIndex, vertexIndex + 2 );
				lineArray.push( vertexIndex + 1, vertexIndex + 2 );

				vertexIndex += 3;

			} else if ( face instanceof THREE.Face4 ) {

				v1 = object.geometry.vertices[ face.a ].position;
				v2 = object.geometry.vertices[ face.b ].position;
				v3 = object.geometry.vertices[ face.c ].position;
				v4 = object.geometry.vertices[ face.d ].position;

				vertexArray.push( v1.x, v1.y, v1.z );
				vertexArray.push( v2.x, v2.y, v2.z );
				vertexArray.push( v3.x, v3.y, v3.z );
				vertexArray.push( v4.x, v4.y, v4.z );

313
				if ( vertexNormals.length == 4 && useSmoothNormals ) {
314

M
Mr.doob 已提交
315 316 317 318 319
					for ( i = 0; i < 4; i ++ ) {

						normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );

					}
320 321 322

				} else {

M
Mr.doob 已提交
323 324 325 326 327
					for ( i = 0; i < 4; i ++ ) {

						normalArray.push( normal.x, normal.y, normal.z );

					}
328 329 330 331 332

				}

				if ( uv ) {

M
Mr.doob 已提交
333 334 335 336
					for ( i = 0; i < 4; i ++ ) {

						uvArray.push( uv[ i ].u, uv[ i ].v );
					}
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

				}

				faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
				faceArray.push( vertexIndex, vertexIndex + 2, vertexIndex + 3 );

				// TODO: don't add lines that already exist (faces sharing edge)

				lineArray.push( vertexIndex, vertexIndex + 1 );
				lineArray.push( vertexIndex, vertexIndex + 2 );
				lineArray.push( vertexIndex, vertexIndex + 3 );
				lineArray.push( vertexIndex + 1, vertexIndex + 2 );
				lineArray.push( vertexIndex + 2, vertexIndex + 3 );

				vertexIndex += 4;
M
Mr.doob 已提交
352

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
			}
		}

		if ( !vertexArray.length ) {

			return;

		}

		materialFaceGroup.__webGLVertexBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( vertexArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLNormalBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( normalArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLUVBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( uvArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLFaceBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
		_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( faceArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLLineBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
		_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( lineArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLFaceCount = faceArray.length;
		materialFaceGroup.__webGLLineCount = lineArray.length;

	};

	this.renderBuffer = function ( material, materialFaceGroup ) {

389 390
		var mColor, mOpacity, mReflectivity,
			mWireframe, mLineWidth, mBlending,
A
alteredq 已提交
391
			mAmbient, mSpecular, mShininess,
392 393
			mMap, envMap, mixEnvMap,
			mRefractionRatio, useRefract;
394
		
M
Mr.doob 已提交
395

A
alteredq 已提交
396 397 398
		if ( material instanceof THREE.MeshPhongMaterial ||
			 material instanceof THREE.MeshLambertMaterial ||
			 material instanceof THREE.MeshBasicMaterial ) {
M
Mr.doob 已提交
399

A
alteredq 已提交
400 401
			mColor = material.color;
			mOpacity = material.opacity;
M
Mr.doob 已提交
402

A
alteredq 已提交
403 404
			mWireframe = material.wireframe;
			mLineWidth = material.wireframe_linewidth;
M
Mr.doob 已提交
405

A
alteredq 已提交
406
			mBlending = material.blending;
M
Mr.doob 已提交
407

A
alteredq 已提交
408
			mMap = material.map;
409
			envMap = material.env_map;
410 411 412

			mixEnvMap = material.combine == THREE.Mix;
			mReflectivity = material.reflectivity;
M
Mr.doob 已提交
413

414 415
			useRefract = material.env_map && material.env_map.mapping == THREE.RefractionMap;
			mRefractionRatio = material.refraction_ratio;
M
Mr.doob 已提交
416

A
alteredq 已提交
417
			_gl.uniform4f( _program.mColor,  mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
M
Mr.doob 已提交
418

419
			_gl.uniform1i( _program.mixEnvMap, mixEnvMap );
420
			_gl.uniform1f( _program.mReflectivity, mReflectivity );
M
Mr.doob 已提交
421

422 423
			_gl.uniform1i( _program.useRefract, useRefract );
			_gl.uniform1f( _program.mRefractionRatio, mRefractionRatio );
M
Mr.doob 已提交
424

A
alteredq 已提交
425
		}
M
Mr.doob 已提交
426

427
		if ( material instanceof THREE.MeshNormalMaterial ) {
M
Mr.doob 已提交
428

429 430
			mOpacity = material.opacity;
			mBlending = material.blending;
M
Mr.doob 已提交
431

432
			_gl.uniform1f( _program.mOpacity, mOpacity );
M
Mr.doob 已提交
433

434
			_gl.uniform1i( _program.material, NORMAL );
M
Mr.doob 已提交
435

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

438
			mOpacity = material.opacity;
M
Mr.doob 已提交
439

440 441
			mWireframe = material.wireframe;
			mLineWidth = material.wireframe_linewidth;
M
Mr.doob 已提交
442

443
			_gl.uniform1f( _program.mOpacity, mOpacity );
M
Mr.doob 已提交
444

445 446 447
			_gl.uniform1f( _program.m2Near, material.__2near );
			_gl.uniform1f( _program.mFarPlusNear, material.__farPlusNear );
			_gl.uniform1f( _program.mFarMinusNear, material.__farMinusNear );
M
Mr.doob 已提交
448

449
			_gl.uniform1i( _program.material, DEPTH );
M
Mr.doob 已提交
450

451
		} else if ( material instanceof THREE.MeshPhongMaterial ) {
452 453 454

			mAmbient  = material.ambient;
			mSpecular = material.specular;
A
alteredq 已提交
455
			mShininess = material.shininess;
M
Mr.doob 已提交
456

A
alteredq 已提交
457 458 459
			_gl.uniform4f( _program.mAmbient,  mAmbient.r,  mAmbient.g,  mAmbient.b,  mOpacity );
			_gl.uniform4f( _program.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, mOpacity );
			_gl.uniform1f( _program.mShininess, mShininess );
M
Mr.doob 已提交
460

461 462
			_gl.uniform1i( _program.material, PHONG );

A
alteredq 已提交
463
		} else if ( material instanceof THREE.MeshLambertMaterial ) {
M
Mr.doob 已提交
464

A
alteredq 已提交
465
			_gl.uniform1i( _program.material, LAMBERT );
466

A
alteredq 已提交
467
		} else if ( material instanceof THREE.MeshBasicMaterial ) {
468

A
alteredq 已提交
469
			_gl.uniform1i( _program.material, BASIC );
470

M
Mr.doob 已提交
471 472 473
		} else if ( material instanceof THREE.MeshCubeMaterial ) {

			_gl.uniform1i( _program.material, CUBE );
M
Mr.doob 已提交
474

M
Mr.doob 已提交
475 476
			envMap = material.env_map;

M
Mr.doob 已提交
477
		}
478
		
A
alteredq 已提交
479
		if ( mMap ) {
480

481
			if ( !material.__webGLTexture && material.map.image.loaded ) {
482 483 484

				material.__webGLTexture = _gl.createTexture();
				_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
485 486 487 488 489
				_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.map.image );
				
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, paramThreeToGL( material.map.wrap_s ) );
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, paramThreeToGL( material.map.wrap_t ) );
				
490 491 492 493 494 495 496 497 498
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
				_gl.generateMipmap( _gl.TEXTURE_2D );
				_gl.bindTexture( _gl.TEXTURE_2D, null );

			}

			_gl.activeTexture( _gl.TEXTURE0 );
			_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
A
alteredq 已提交
499
			_gl.uniform1i( _program.tMap,  0 );
500

A
alteredq 已提交
501
			_gl.uniform1i( _program.enableMap, 1 );
502

A
alteredq 已提交
503
		} else {
M
Mr.doob 已提交
504

A
alteredq 已提交
505
			_gl.uniform1i( _program.enableMap, 0 );
M
Mr.doob 已提交
506

507
		}
M
Mr.doob 已提交
508

509
		if ( envMap ) {
M
Mr.doob 已提交
510 511 512 513 514 515 516

			if ( material.env_map && material.env_map instanceof THREE.TextureCube &&
			material.env_map.image.length == 6 ) {

				if ( !material.env_map.image.__webGLTextureCube &&
				!material.env_map.image.__cubeMapInitialized && material.env_map.image.loadCount == 6 ) {

M
Mr.doob 已提交
517
					material.env_map.image.__webGLTextureCube = _gl.createTexture();
M
Mr.doob 已提交
518

M
Mr.doob 已提交
519
					_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, material.env_map.image.__webGLTextureCube );
M
Mr.doob 已提交
520

521 522
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
M
Mr.doob 已提交
523

524 525
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
M
Mr.doob 已提交
526 527 528 529 530

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

						_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[ i ] );

531
					}
M
Mr.doob 已提交
532

533
					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
M
Mr.doob 已提交
534

535
					_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
M
Mr.doob 已提交
536

M
Mr.doob 已提交
537
					material.env_map.image.__cubeMapInitialized = true;
M
Mr.doob 已提交
538

539
				}
M
Mr.doob 已提交
540

541
				_gl.activeTexture( _gl.TEXTURE1 );
M
Mr.doob 已提交
542
				_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, material.env_map.image.__webGLTextureCube );
543
				_gl.uniform1i( _program.tCube,  1 );
M
Mr.doob 已提交
544

545
			}
M
Mr.doob 已提交
546

547
			_gl.uniform1i( _program.enableCubeMap, 1 );
M
Mr.doob 已提交
548

549
		} else {
M
Mr.doob 已提交
550

551
			_gl.uniform1i( _program.enableCubeMap, 0 );
M
Mr.doob 已提交
552

553
		}
M
Mr.doob 已提交
554

555
		// vertices
M
Mr.doob 已提交
556

557 558 559 560
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
		_gl.vertexAttribPointer( _program.position, 3, _gl.FLOAT, false, 0, 0 );

		// normals
M
Mr.doob 已提交
561

562 563 564 565
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
		_gl.vertexAttribPointer( _program.normal, 3, _gl.FLOAT, false, 0, 0 );

		// uvs
M
Mr.doob 已提交
566

A
alteredq 已提交
567
		if ( mMap ) {
568 569 570 571 572 573 574 575 576 577 578 579 580

			_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );

			_gl.enableVertexAttribArray( _program.uv );
			_gl.vertexAttribPointer( _program.uv, 2, _gl.FLOAT, false, 0, 0 );

		} else {

			_gl.disableVertexAttribArray( _program.uv );

		}

		// render triangles
M
Mr.doob 已提交
581

A
alteredq 已提交
582
		if ( ! mWireframe ) {
583 584 585 586 587

			_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
			_gl.drawElements( _gl.TRIANGLES, materialFaceGroup.__webGLFaceCount, _gl.UNSIGNED_SHORT, 0 );

		// render lines
M
Mr.doob 已提交
588

A
alteredq 已提交
589
		} else {
590

A
alteredq 已提交
591
			_gl.lineWidth( mLineWidth );
592 593 594 595 596 597 598
			_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
			_gl.drawElements( _gl.LINES, materialFaceGroup.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );

		}

	};

599
	this.renderPass = function ( object, materialFaceGroup, blending, transparent ) {
M
Mr.doob 已提交
600

M
Mr.doob 已提交
601
		var i, l, m, ml, material, meshMaterial;
M
Mr.doob 已提交
602

M
Mr.doob 已提交
603
		for ( m = 0, ml = object.material.length; m < ml; m++ ) {
604

M
Mr.doob 已提交
605
			meshMaterial = object.material[ m ];
606

M
Mr.doob 已提交
607
			if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
608

M
Mr.doob 已提交
609
				for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
610

M
Mr.doob 已提交
611
					material = materialFaceGroup.material[ i ];
612
					if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
M
Mr.doob 已提交
613

M
Mr.doob 已提交
614
						this.setBlending( material.blending );
615
						this.renderBuffer( material, materialFaceGroup );
M
Mr.doob 已提交
616

617 618
					}

M
Mr.doob 已提交
619
				}
620

M
Mr.doob 已提交
621
			} else {
622

M
Mr.doob 已提交
623
				material = meshMaterial;
624
				if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
M
Mr.doob 已提交
625

M
Mr.doob 已提交
626 627
					this.setBlending( material.blending );
					this.renderBuffer( material, materialFaceGroup );
628 629 630
				}

			}
631 632

		}
M
Mr.doob 已提交
633

634 635
	};

M
Mr.doob 已提交
636
	this.render = function( scene, camera ) {
M
Mr.doob 已提交
637

M
Mr.doob 已提交
638
		var o, ol;
M
Mr.doob 已提交
639

M
Mr.doob 已提交
640
		this.initWebGLObjects( scene );
M
Mr.doob 已提交
641

642 643 644 645 646 647
		if ( this.autoClear ) {

			this.clear();

		}

648 649 650 651
		camera.autoUpdateMatrix && camera.updateMatrix();
		_gl.uniform3f( _program.cameraPosition, camera.position.x, camera.position.y, camera.position.z );

		this.setupLights( scene );
652

M
Mr.doob 已提交
653
		// opaque pass
M
Mr.doob 已提交
654

M
Mr.doob 已提交
655
		for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
M
Mr.doob 已提交
656

M
Mr.doob 已提交
657
			webGLObject = scene.__webGLObjects[ o ];
658 659
			
			if ( webGLObject.__object.visible ) {
M
Mr.doob 已提交
660

661 662 663 664
				this.setupMatrices( webGLObject.__object, camera );
				this.renderPass( webGLObject.__object, webGLObject, THREE.NormalBlending, false );
				
			}
M
Mr.doob 已提交
665

M
Mr.doob 已提交
666
		}
M
Mr.doob 已提交
667

M
Mr.doob 已提交
668
		// transparent pass
M
Mr.doob 已提交
669

M
Mr.doob 已提交
670
		for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
M
Mr.doob 已提交
671

M
Mr.doob 已提交
672
			webGLObject = scene.__webGLObjects[ o ];
M
Mr.doob 已提交
673

674 675 676
			if ( webGLObject.__object.visible ) {
				
				this.setupMatrices( webGLObject.__object, camera );
677

678 679 680 681 682 683 684 685 686
				// opaque blended materials
				
				this.renderPass( webGLObject.__object, webGLObject, THREE.AdditiveBlending, false );
				this.renderPass( webGLObject.__object, webGLObject, THREE.SubtractiveBlending, false );
				
				// transparent blended materials
				
				this.renderPass( webGLObject.__object, webGLObject, THREE.AdditiveBlending, true );
				this.renderPass( webGLObject.__object, webGLObject, THREE.SubtractiveBlending, true );
687

688 689 690 691 692
				// transparent normal materials
				
				this.renderPass( webGLObject.__object, webGLObject, THREE.NormalBlending, true );
				
			}
M
Mr.doob 已提交
693

M
Mr.doob 已提交
694
		}
M
Mr.doob 已提交
695

M
Mr.doob 已提交
696
	};
M
Mr.doob 已提交
697

M
Mr.doob 已提交
698
	this.initWebGLObjects = function( scene ) {
M
Mr.doob 已提交
699

M
Mr.doob 已提交
700
		var o, ol, object, mf, materialFaceGroup;
M
Mr.doob 已提交
701

M
Mr.doob 已提交
702
		if ( !scene.__webGLObjects ) {
M
Mr.doob 已提交
703

M
Mr.doob 已提交
704
			scene.__webGLObjects = [];
M
Mr.doob 已提交
705

M
Mr.doob 已提交
706
		}
M
Mr.doob 已提交
707

708 709 710 711 712 713
		for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {

			object = scene.objects[ o ];

			if ( object instanceof THREE.Mesh ) {

M
Mr.doob 已提交
714
				// create separate VBOs per material
M
Mr.doob 已提交
715

M
Mr.doob 已提交
716 717 718 719 720
				for ( mf in object.materialFaceGroup ) {

					materialFaceGroup = object.materialFaceGroup[ mf ];

					// initialise buffers on the first access
M
Mr.doob 已提交
721

M
Mr.doob 已提交
722 723 724 725 726 727 728
					if( ! materialFaceGroup.__webGLVertexBuffer ) {

						this.createBuffers( object, mf );
						materialFaceGroup.__object = object;
						scene.__webGLObjects.push( materialFaceGroup );

					}
M
Mr.doob 已提交
729

M
Mr.doob 已提交
730
				}
731

M
Mr.doob 已提交
732 733
			}/* else if ( object instanceof THREE.Line ) {

M
Mr.doob 已提交
734
			} else if ( object instanceof THREE.Particle ) {
M
Mr.doob 已提交
735 736 737

			}*/

M
Mr.doob 已提交
738
		}
739 740 741 742 743 744

	};

	this.removeObject = function ( scene, object ) {

		var o, ol, zobject;
745 746 747
		
		for ( o = scene.__webGLObjects.length - 1; o >= 0; o-- ) {
			
748 749 750
			zobject = scene.__webGLObjects[ o ].__object;
			
			if ( object == zobject ) {
751 752 753 754 755 756 757

				scene.__webGLObjects.splice( o, 1 );

			}
			
		}
		
M
Mr.doob 已提交
758
	};
M
Mr.doob 已提交
759

M
Mr.doob 已提交
760
	this.setupMatrices = function ( object, camera ) {
761

M
Mr.doob 已提交
762
		object.autoUpdateMatrix && object.updateMatrix();
763

M
Mr.doob 已提交
764
		_modelViewMatrix.multiply( camera.matrix, object.matrix );
765

M
Mr.doob 已提交
766 767 768
		_program.viewMatrixArray = new Float32Array( camera.matrix.flatten() );
		_program.modelViewMatrixArray = new Float32Array( _modelViewMatrix.flatten() );
		_program.projectionMatrixArray = new Float32Array( camera.projectionMatrix.flatten() );
769

M
Mr.doob 已提交
770 771
		_normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
		_program.normalMatrixArray = new Float32Array( _normalMatrix.m );
772

M
Mr.doob 已提交
773 774 775 776 777
		_gl.uniformMatrix4fv( _program.viewMatrix, false, _program.viewMatrixArray );
		_gl.uniformMatrix4fv( _program.modelViewMatrix, false, _program.modelViewMatrixArray );
		_gl.uniformMatrix4fv( _program.projectionMatrix, false, _program.projectionMatrixArray );
		_gl.uniformMatrix3fv( _program.normalMatrix, false, _program.normalMatrixArray );
		_gl.uniformMatrix4fv( _program.objMatrix, false, new Float32Array( object.matrix.flatten() ) );
778

M
Mr.doob 已提交
779
	};
780

M
Mr.doob 已提交
781

M
Mr.doob 已提交
782
	this.setBlending = function( blending ) {
M
Mr.doob 已提交
783

M
Mr.doob 已提交
784
		switch ( blending ) {
785

M
Mr.doob 已提交
786
			case THREE.AdditiveBlending:
787

M
Mr.doob 已提交
788 789
				_gl.blendEquation( _gl.FUNC_ADD );
				_gl.blendFunc( _gl.ONE, _gl.ONE );
M
Mr.doob 已提交
790

M
Mr.doob 已提交
791
				break;
792

M
Mr.doob 已提交
793
			case THREE.SubtractiveBlending:
794

M
Mr.doob 已提交
795 796
				//_gl.blendEquation( _gl.FUNC_SUBTRACT );
				_gl.blendFunc( _gl.DST_COLOR, _gl.ZERO );
M
Mr.doob 已提交
797

M
Mr.doob 已提交
798
				break;
M
Mr.doob 已提交
799

M
Mr.doob 已提交
800
			default:
M
Mr.doob 已提交
801

M
Mr.doob 已提交
802 803
				_gl.blendEquation( _gl.FUNC_ADD );
				_gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
M
Mr.doob 已提交
804

M
Mr.doob 已提交
805
				break;
N
Nicolas Garcia Belmonte 已提交
806
		}
M
Mr.doob 已提交
807

N
Nicolas Garcia Belmonte 已提交
808
	};
M
Mr.doob 已提交
809

810
	this.setFaceCulling = function( cullFace, frontFace ) {
M
Mr.doob 已提交
811

812
		if ( cullFace ) {
M
Mr.doob 已提交
813

814
			if ( !frontFace || frontFace == "ccw" ) {
M
Mr.doob 已提交
815

816
				_gl.frontFace( _gl.CCW );
M
Mr.doob 已提交
817

818
			} else {
M
Mr.doob 已提交
819

820 821
				_gl.frontFace( _gl.CW );
			}
M
Mr.doob 已提交
822

823
			if( cullFace == "back" ) {
M
Mr.doob 已提交
824

825
				_gl.cullFace( _gl.BACK );
M
Mr.doob 已提交
826

827
			} else if( cullFace == "front" ) {
M
Mr.doob 已提交
828

829
				_gl.cullFace( _gl.FRONT );
M
Mr.doob 已提交
830

831
			} else {
M
Mr.doob 已提交
832

833 834
				_gl.cullFace( _gl.FRONT_AND_BACK );
			}
M
Mr.doob 已提交
835

836
			_gl.enable( _gl.CULL_FACE );
M
Mr.doob 已提交
837

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

840 841 842 843
			_gl.disable( _gl.CULL_FACE );
		}

	};
N
Nicolas Garcia Belmonte 已提交
844 845 846 847 848

	function initGL() {

		try {

U
unknown 已提交
849
			_gl = _canvas.getContext( 'experimental-webgl', { antialias: true} );
N
Nicolas Garcia Belmonte 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865

		} catch(e) { }

		if (!_gl) {

			alert("WebGL not supported");
			throw "cannot create webgl context";

		}

		_gl.clearColor( 0, 0, 0, 1 );
		_gl.clearDepth( 1 );

		_gl.enable( _gl.DEPTH_TEST );
		_gl.depthFunc( _gl.LEQUAL );

866 867
		_gl.frontFace( _gl.CCW );
		_gl.cullFace( _gl.BACK );
868
		_gl.enable( _gl.CULL_FACE );
M
Mr.doob 已提交
869

N
Nicolas Garcia Belmonte 已提交
870
		_gl.enable( _gl.BLEND );
U
unknown 已提交
871
		//_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
M
Mr.doob 已提交
872
		//_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); // cool!
873
		_gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
N
Nicolas Garcia Belmonte 已提交
874 875
		_gl.clearColor( 0, 0, 0, 0 );

876
	};
N
Nicolas Garcia Belmonte 已提交
877

878
	function generateFragmentShader( maxDirLights, maxPointLights ) {
M
Mr.doob 已提交
879

880
		var chunks = [
881

882 883 884
			"#ifdef GL_ES",
			"precision highp float;",
			"#endif",
M
Mr.doob 已提交
885

886 887
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
M
Mr.doob 已提交
888

M
Mr.doob 已提交
889
			"uniform int material;", // 0 - Basic, 1 - Lambert, 2 - Phong, 3 - Depth, 4 - Normal, 5 - Cube
890

A
alteredq 已提交
891
			"uniform bool enableMap;",
892
			"uniform bool enableCubeMap;",
893
			"uniform bool mixEnvMap;",
M
Mr.doob 已提交
894

895 896 897
			"uniform samplerCube tCube;",
			"uniform float mReflectivity;",

A
alteredq 已提交
898
			"uniform sampler2D tMap;",
899
			"uniform vec4 mColor;",
900
			"uniform float mOpacity;",
901

902
			"uniform vec4 mAmbient;",
903
			"uniform vec4 mSpecular;",
904
			"uniform float mShininess;",
905

906 907 908
			"uniform float m2Near;",
			"uniform float mFarPlusNear;",
			"uniform float mFarMinusNear;",
M
Mr.doob 已提交
909

910 911
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
M
Mr.doob 已提交
912

913 914
			maxDirLights ? "uniform mat4 viewMatrix;" : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
M
Mr.doob 已提交
915

916
			"varying vec3 vNormal;",
917
			"varying vec2 vUv;",
M
Mr.doob 已提交
918

919 920
			"varying vec3 vLightWeighting;",

921
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
M
Mr.doob 已提交
922

923
			"varying vec3 vViewPosition;",
M
Mr.doob 已提交
924

925
			"varying vec3 vReflect;",
M
Mr.doob 已提交
926

M
Mr.doob 已提交
927
			"uniform vec3 cameraPosition;",
M
Mr.doob 已提交
928

929
			"void main() {",
930

A
alteredq 已提交
931
				"vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
932
				"vec4 cubeColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
933

934
				// diffuse map
M
Mr.doob 已提交
935

A
alteredq 已提交
936
				"if ( enableMap ) {",
M
Mr.doob 已提交
937

A
alteredq 已提交
938
					"mapColor = texture2D( tMap, vUv );",
M
Mr.doob 已提交
939

A
alteredq 已提交
940
				"}",
941

942
				// cube map
M
Mr.doob 已提交
943

944
				"if ( enableCubeMap ) {",
M
Mr.doob 已提交
945

946
					"cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
M
Mr.doob 已提交
947

948 949
				"}",

M
Mr.doob 已提交
950
				// Cube
M
Mr.doob 已提交
951

M
Mr.doob 已提交
952 953 954 955 956
				"if ( material == 5 ) { ",

					"vec3 wPos = cameraPosition - vViewPosition;",
					"gl_FragColor = textureCube( tCube, vec3( -wPos.x, wPos.yz ) );",

957
				// Normals
M
Mr.doob 已提交
958

M
Mr.doob 已提交
959
				"} else if ( material == 4 ) { ",
M
Mr.doob 已提交
960

961
					"gl_FragColor = vec4( 0.5*normalize( vNormal ) + vec3(0.5, 0.5, 0.5), mOpacity );",
M
Mr.doob 已提交
962

963
				// Depth
M
Mr.doob 已提交
964

965
				"} else if ( material == 3 ) { ",
M
Mr.doob 已提交
966 967

					// this breaks shader validation in Chrome 9.0.576.0 dev
968 969 970 971
					// and also latest continuous build Chromium 9.0.583.0 (66089)
					// (curiously it works in Chrome 9.0.576.0 canary build and Firefox 4b7)
					//"float w = 1.0 - ( m2Near / ( mFarPlusNear - gl_FragCoord.z * mFarMinusNear ) );",
					"float w = 0.5;",
M
Mr.doob 已提交
972

973
					"gl_FragColor = vec4( w, w, w, mOpacity );",
M
Mr.doob 已提交
974

975 976
				// Blinn-Phong
				// based on o3d example
M
Mr.doob 已提交
977 978

				"} else if ( material == 2 ) { ",
979 980 981 982

					"vec3 normal = normalize( vNormal );",
					"vec3 viewPosition = normalize( vViewPosition );",

983
					// point lights
M
Mr.doob 已提交
984

985 986 987
					maxPointLights ? "vec4 pointDiffuse  = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
					maxPointLights ? "vec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",

988
					maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
M
Mr.doob 已提交
989

990 991
					maxPointLights ? 	"vec3 pointVector = normalize( vPointLightVector[ i ] );" : "",
					maxPointLights ? 	"vec3 pointHalfVector = normalize( vPointLightVector[ i ] + vViewPosition );" : "",
M
Mr.doob 已提交
992

993 994 995 996 997 998
					maxPointLights ? 	"float pointDotNormalHalf = dot( normal, pointHalfVector );" : "",
					maxPointLights ? 	"float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );" : "",

					// Ternary conditional is from the original o3d shader. Here it produces abrupt dark cutoff artefacts.
					// Using just pow works ok in Chrome, but makes different artefact in Firefox 4.
					// Zeroing on negative pointDotNormalHalf seems to work in both.
M
Mr.doob 已提交
999

1000 1001
					//"float specularCompPoint = dot( normal, pointVector ) < 0.0 || pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
					//"float specularCompPoint = pow( pointDotNormalHalf, mShininess );",
1002
					//"float pointSpecularWeight = pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
1003

1004 1005
					// Ternary conditional inside for loop breaks Chrome shader linking.
					// Must do it with if.
1006

1007 1008 1009
					maxPointLights ? 	"float pointSpecularWeight = 0.0;" : "",
					maxPointLights ? 	"if ( pointDotNormalHalf >= 0.0 )" : "",
					maxPointLights ? 		"pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
M
Mr.doob 已提交
1010

A
alteredq 已提交
1011
					maxPointLights ? 	"pointDiffuse  += mColor * pointDiffuseWeight;" : "",
1012
					maxPointLights ? 	"pointSpecular += mSpecular * pointSpecularWeight;" : "",
M
Mr.doob 已提交
1013

1014
					maxPointLights ? "}" : "",
1015

1016 1017 1018 1019
					// directional lights

					maxDirLights ? "vec4 dirDiffuse  = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
					maxDirLights ? "vec4 dirSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
M
Mr.doob 已提交
1020

1021
					maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
1022

1023
					maxDirLights ?		"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
1024

1025 1026
					maxDirLights ? 		"vec3 dirVector = normalize( lDirection.xyz );" : "",
					maxDirLights ? 		"vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );" : "",
M
Mr.doob 已提交
1027

1028
					maxDirLights ? 		"float dirDotNormalHalf = dot( normal, dirHalfVector );" : "",
1029

M
Mr.doob 已提交
1030 1031
					maxDirLights ? 		"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );" : "",

1032 1033 1034
					maxDirLights ? 		"float dirSpecularWeight = 0.0;" : "",
					maxDirLights ? 		"if ( dirDotNormalHalf >= 0.0 )" : "",
					maxDirLights ? 			"dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
1035

A
alteredq 已提交
1036
					maxDirLights ? 		"dirDiffuse  += mColor * dirDiffuseWeight;" : "",
1037 1038 1039 1040 1041
					maxDirLights ? 		"dirSpecular += mSpecular * dirSpecularWeight;" : "",

					maxDirLights ? "}" : "",

					// all lights contribution summation
M
Mr.doob 已提交
1042

1043 1044 1045 1046 1047
					"vec4 totalLight = mAmbient;",
					maxDirLights   ? "totalLight += dirDiffuse + dirSpecular;" : "",
					maxPointLights ? "totalLight += pointDiffuse + pointSpecular;" : "",

					// looks nicer with weighting
M
Mr.doob 已提交
1048

1049
					"if ( mixEnvMap ) {",
M
Mr.doob 已提交
1050

1051
						"gl_FragColor = vec4( mix( mapColor.rgb * totalLight.xyz * vLightWeighting, cubeColor.rgb, mReflectivity ), mapColor.a );",
M
Mr.doob 已提交
1052

1053
					"} else {",
M
Mr.doob 已提交
1054

1055
						"gl_FragColor = vec4( mapColor.rgb * cubeColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
M
Mr.doob 已提交
1056

1057
					"}",
M
Mr.doob 已提交
1058

A
alteredq 已提交
1059
				// Lambert: diffuse lighting
M
Mr.doob 已提交
1060 1061

				"} else if ( material == 1 ) {",
1062

1063
				"if ( mixEnvMap ) {",
M
Mr.doob 已提交
1064

1065
						"gl_FragColor = vec4( mix( mColor.rgb * mapColor.rgb * vLightWeighting, cubeColor.rgb, mReflectivity ), mColor.a * mapColor.a );",
M
Mr.doob 已提交
1066

1067
					"} else {",
M
Mr.doob 已提交
1068

1069
						"gl_FragColor = vec4( mColor.rgb * mapColor.rgb * cubeColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
M
Mr.doob 已提交
1070

1071
					"}",
M
Mr.doob 已提交
1072

A
alteredq 已提交
1073
				// Basic: unlit color / texture
M
Mr.doob 已提交
1074 1075

				"} else {",
1076

1077 1078 1079
					"if ( mixEnvMap ) {",

						"gl_FragColor = mix( mColor * mapColor, cubeColor, mReflectivity );",
M
Mr.doob 已提交
1080

1081 1082 1083
					"} else {",

						"gl_FragColor = mColor * mapColor * cubeColor;",
M
Mr.doob 已提交
1084

1085
					"}",
M
Mr.doob 已提交
1086

1087 1088
				"}",

1089
			"}" ];
M
Mr.doob 已提交
1090

1091
		return chunks.join("\n");
M
Mr.doob 已提交
1092

1093
	};
M
Mr.doob 已提交
1094

1095
	function generateVertexShader( maxDirLights, maxPointLights ) {
M
Mr.doob 已提交
1096

1097
		var chunks = [
M
Mr.doob 已提交
1098

1099 1100
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
M
Mr.doob 已提交
1101

1102 1103
			"attribute vec3 position;",
			"attribute vec3 normal;",
1104
			"attribute vec2 uv;",
1105

1106 1107
			"uniform vec3 cameraPosition;",

1108
			"uniform bool enableLighting;",
1109
			"uniform bool useRefract;",
M
Mr.doob 已提交
1110

1111 1112
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
M
Mr.doob 已提交
1113

1114
			"uniform vec3 ambientLightColor;",
M
Mr.doob 已提交
1115

1116 1117
			maxDirLights ? "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];"     : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
1118

1119 1120
			maxPointLights ? "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];"    : "",
			maxPointLights ? "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];" : "",
1121

1122
			"uniform mat4 objMatrix;",
1123
			"uniform mat4 viewMatrix;",
1124
			"uniform mat4 modelViewMatrix;",
1125
			"uniform mat4 projectionMatrix;",
1126
			"uniform mat3 normalMatrix;",
1127 1128

			"varying vec3 vNormal;",
1129
			"varying vec2 vUv;",
M
Mr.doob 已提交
1130

1131
			"varying vec3 vLightWeighting;",
1132

1133
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
M
Mr.doob 已提交
1134

1135
			"varying vec3 vViewPosition;",
M
Mr.doob 已提交
1136

1137
			"varying vec3 vReflect;",
1138
			"uniform float mRefractionRatio;",
1139

1140
			"void main(void) {",
1141

1142
				// world space
M
Mr.doob 已提交
1143

1144 1145
				"vec4 mPosition = objMatrix * vec4( position, 1.0 );",
				"vViewPosition = cameraPosition - mPosition.xyz;",
M
Mr.doob 已提交
1146

A
alteredq 已提交
1147 1148 1149
				// this doesn't work on Mac
				//"vec3 nWorld = mat3(objMatrix) * normal;",
				"vec3 nWorld = mat3( objMatrix[0].xyz, objMatrix[1].xyz, objMatrix[2].xyz ) * normal;",
M
Mr.doob 已提交
1150

1151
				// eye space
M
Mr.doob 已提交
1152

1153
				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
1154
				"vec3 transformedNormal = normalize( normalMatrix * normal );",
1155

1156
				"if ( !enableLighting ) {",
1157

1158
					"vLightWeighting = vec3( 1.0, 1.0, 1.0 );",
1159 1160 1161

				"} else {",

1162
					"vLightWeighting = ambientLightColor;",
M
Mr.doob 已提交
1163

1164
					// directional lights
M
Mr.doob 已提交
1165

1166
					maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
1167
					maxDirLights ?		"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
1168
					maxDirLights ?		"float directionalLightWeighting = max( dot( transformedNormal, normalize(lDirection.xyz ) ), 0.0 );" : "",
1169 1170
					maxDirLights ?		"vLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;" : "",
					maxDirLights ? "}" : "",
M
Mr.doob 已提交
1171

1172
					// point lights
M
Mr.doob 已提交
1173

1174
					maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
1175 1176 1177 1178 1179
					maxPointLights ? 	"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );" : "",
					maxPointLights ? 	"vPointLightVector[ i ] = normalize( lPosition.xyz - mvPosition.xyz );" : "",
					maxPointLights ? 	"float pointLightWeighting = max( dot( transformedNormal, vPointLightVector[ i ] ), 0.0 );" : "",
					maxPointLights ? 	"vLightWeighting += pointLightColor[ i ] * pointLightWeighting;" : "",
					maxPointLights ? "}" : "",
M
Mr.doob 已提交
1180

1181
				"}",
1182

1183
				"vNormal = transformedNormal;",
1184
				"vUv = uv;",
1185

1186
				"if ( useRefract ) {",
M
Mr.doob 已提交
1187

1188
					"vReflect = refract( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz), mRefractionRatio );",
M
Mr.doob 已提交
1189

1190
				"} else {",
M
Mr.doob 已提交
1191

1192
					"vReflect = reflect( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz) );",
M
Mr.doob 已提交
1193

1194
				"}",
M
Mr.doob 已提交
1195

1196
				"gl_Position = projectionMatrix * mvPosition;",
1197

1198
			"}" ];
M
Mr.doob 已提交
1199

1200
		return chunks.join("\n");
M
Mr.doob 已提交
1201

1202
	};
M
Mr.doob 已提交
1203

1204 1205 1206
	function initProgram( maxDirLights, maxPointLights ) {

		_program = _gl.createProgram();
M
Mr.doob 已提交
1207

1208 1209
		//log ( generateVertexShader( maxDirLights, maxPointLights ) );
		//log ( generateFragmentShader( maxDirLights, maxPointLights ) );
M
Mr.doob 已提交
1210

1211 1212
		_gl.attachShader( _program, getShader( "fragment", generateFragmentShader( maxDirLights, maxPointLights ) ) );
		_gl.attachShader( _program, getShader( "vertex",   generateVertexShader( maxDirLights, maxPointLights ) ) );
N
Nicolas Garcia Belmonte 已提交
1213 1214 1215 1216 1217 1218 1219

		_gl.linkProgram( _program );

		if ( !_gl.getProgramParameter( _program, _gl.LINK_STATUS ) ) {

			alert( "Could not initialise shaders" );

1220 1221
			alert( "VALIDATE_STATUS: " + _gl.getProgramParameter( _program, _gl.VALIDATE_STATUS ) );
			alert( _gl.getError() );
N
Nicolas Garcia Belmonte 已提交
1222
		}
M
Mr.doob 已提交
1223

N
Nicolas Garcia Belmonte 已提交
1224 1225 1226

		_gl.useProgram( _program );

1227
		// matrices
M
Mr.doob 已提交
1228

N
Nicolas Garcia Belmonte 已提交
1229
		_program.viewMatrix = _gl.getUniformLocation( _program, "viewMatrix" );
1230
		_program.modelViewMatrix = _gl.getUniformLocation( _program, "modelViewMatrix" );
N
Nicolas Garcia Belmonte 已提交
1231
		_program.projectionMatrix = _gl.getUniformLocation( _program, "projectionMatrix" );
1232
		_program.normalMatrix = _gl.getUniformLocation( _program, "normalMatrix" );
1233
		_program.objMatrix = _gl.getUniformLocation( _program, "objMatrix" );
N
Nicolas Garcia Belmonte 已提交
1234

A
alteredq 已提交
1235
		_program.cameraPosition = _gl.getUniformLocation( _program, 'cameraPosition' );
1236

1237
		// lights
M
Mr.doob 已提交
1238

A
alteredq 已提交
1239
		_program.enableLighting = _gl.getUniformLocation( _program, 'enableLighting' );
M
Mr.doob 已提交
1240

A
alteredq 已提交
1241
		_program.ambientLightColor = _gl.getUniformLocation( _program, 'ambientLightColor' );
M
Mr.doob 已提交
1242

1243
		if ( maxDirLights ) {
M
Mr.doob 已提交
1244

A
alteredq 已提交
1245 1246 1247
			_program.directionalLightNumber = _gl.getUniformLocation( _program, 'directionalLightNumber' );
			_program.directionalLightColor = _gl.getUniformLocation( _program, 'directionalLightColor' );
			_program.directionalLightDirection = _gl.getUniformLocation( _program, 'directionalLightDirection' );
M
Mr.doob 已提交
1248

1249
		}
1250

1251
		if ( maxPointLights ) {
M
Mr.doob 已提交
1252

A
alteredq 已提交
1253 1254 1255
			_program.pointLightNumber = _gl.getUniformLocation( _program, 'pointLightNumber' );
			_program.pointLightColor = _gl.getUniformLocation( _program, 'pointLightColor' );
			_program.pointLightPosition = _gl.getUniformLocation( _program, 'pointLightPosition' );
M
Mr.doob 已提交
1256

1257
		}
U
unknown 已提交
1258

1259
		// material
M
Mr.doob 已提交
1260

A
alteredq 已提交
1261
		_program.material = _gl.getUniformLocation( _program, 'material' );
M
Mr.doob 已提交
1262

A
alteredq 已提交
1263
		// material properties (Basic / Lambert / Blinn-Phong shader)
M
Mr.doob 已提交
1264

A
alteredq 已提交
1265
		_program.mColor = _gl.getUniformLocation( _program, 'mColor' );
1266
		_program.mOpacity = _gl.getUniformLocation( _program, 'mOpacity' );
1267
		_program.mReflectivity = _gl.getUniformLocation( _program, 'mReflectivity' );
1268

1269
		// material properties (Blinn-Phong shader)
M
Mr.doob 已提交
1270

A
alteredq 已提交
1271 1272 1273
		_program.mAmbient = _gl.getUniformLocation( _program, 'mAmbient' );
		_program.mSpecular = _gl.getUniformLocation( _program, 'mSpecular' );
		_program.mShininess = _gl.getUniformLocation( _program, 'mShininess' );
1274

A
alteredq 已提交
1275
		// texture (diffuse map)
M
Mr.doob 已提交
1276

A
alteredq 已提交
1277
		_program.enableMap = _gl.getUniformLocation( _program, "enableMap" );
1278
		_gl.uniform1i( _program.enableMap, 0 );
M
Mr.doob 已提交
1279

A
alteredq 已提交
1280
		_program.tMap = _gl.getUniformLocation( _program, "tMap" );
1281
		_gl.uniform1i( _program.tMap, 0 );
1282

1283
		// cube texture
M
Mr.doob 已提交
1284

1285
		_program.enableCubeMap = _gl.getUniformLocation( _program, "enableCubeMap" );
1286
		_gl.uniform1i( _program.enableCubeMap, 0 );
M
Mr.doob 已提交
1287

1288
		_program.tCube = _gl.getUniformLocation( _program, "tCube" );
1289
		_gl.uniform1i( _program.tCube, 1 ); // it's important to use non-zero texture unit, otherwise it doesn't work
1290

1291 1292
		_program.mixEnvMap = _gl.getUniformLocation( _program, "mixEnvMap" );
		_gl.uniform1i( _program.mixEnvMap, 0 );
M
Mr.doob 已提交
1293

1294
		// refraction
M
Mr.doob 已提交
1295

1296
		_program.mRefractionRatio = _gl.getUniformLocation( _program, 'mRefractionRatio' );
M
Mr.doob 已提交
1297

1298 1299
		_program.useRefract = _gl.getUniformLocation( _program, "useRefract" );
		_gl.uniform1i( _program.useRefract, 0 );
M
Mr.doob 已提交
1300

1301
		// material properties (Depth)
M
Mr.doob 已提交
1302

1303 1304 1305
		_program.m2Near = _gl.getUniformLocation( _program, 'm2Near' );
		_program.mFarPlusNear = _gl.getUniformLocation( _program, 'mFarPlusNear' );
		_program.mFarMinusNear = _gl.getUniformLocation( _program, 'mFarMinusNear' );
M
Mr.doob 已提交
1306

1307
		// vertex arrays
M
Mr.doob 已提交
1308

N
Nicolas Garcia Belmonte 已提交
1309 1310 1311
		_program.position = _gl.getAttribLocation( _program, "position" );
		_gl.enableVertexAttribArray( _program.position );

1312 1313
		_program.normal = _gl.getAttribLocation( _program, "normal" );
		_gl.enableVertexAttribArray( _program.normal );
1314

U
unknown 已提交
1315 1316 1317 1318
		_program.uv = _gl.getAttribLocation( _program, "uv" );
		_gl.enableVertexAttribArray( _program.uv );


N
Nicolas Garcia Belmonte 已提交
1319
		_program.viewMatrixArray = new Float32Array(16);
1320
		_program.modelViewMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1321
		_program.projectionMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1322

1323
	};
N
Nicolas Garcia Belmonte 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

	function getShader( type, string ) {

		var shader;

		if ( type == "fragment" ) {

			shader = _gl.createShader( _gl.FRAGMENT_SHADER );

		} else if ( type == "vertex" ) {

			shader = _gl.createShader( _gl.VERTEX_SHADER );

		}

		_gl.shaderSource( shader, string );
		_gl.compileShader( shader );

		if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {

			alert( _gl.getShaderInfoLog( shader ) );
			return null;

		}

		return shader;
M
Mr.doob 已提交
1350

1351
	};
N
Nicolas Garcia Belmonte 已提交
1352

1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
	function paramThreeToGL( p ) {
	
		switch ( p ) {
		
		case THREE.Repeat: 	  	   return _gl.REPEAT; break;
		case THREE.ClampToEdge:    return _gl.CLAMP_TO_EDGE; break;
		case THREE.MirroredRepeat: return _gl.MIRRORED_REPEAT; break;
		
		}
		
		return 0;
	};

A
alteredq 已提交
1366
	/* DEBUG
1367
	function getGLParams() {
M
Mr.doob 已提交
1368

1369
		var params  = {
M
Mr.doob 已提交
1370

1371 1372
			'MAX_VARYING_VECTORS': _gl.getParameter( _gl.MAX_VARYING_VECTORS ),
			'MAX_VERTEX_ATTRIBS': _gl.getParameter( _gl.MAX_VERTEX_ATTRIBS ),
M
Mr.doob 已提交
1373

1374 1375 1376
			'MAX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ),
			'MAX_VERTEX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
			'MAX_COMBINED_TEXTURE_IMAGE_UNITS' : _gl.getParameter( _gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ),
M
Mr.doob 已提交
1377

1378 1379 1380
			'MAX_VERTEX_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
			'MAX_FRAGMENT_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_FRAGMENT_UNIFORM_VECTORS )
		}
M
Mr.doob 已提交
1381

1382 1383
		return params;
	};
M
Mr.doob 已提交
1384

1385
	function dumpObject( obj ) {
M
Mr.doob 已提交
1386

1387 1388
		var p, str = "";
		for ( p in obj ) {
M
Mr.doob 已提交
1389

1390
			str += p + ": " + obj[p] + "\n";
M
Mr.doob 已提交
1391

1392
		}
M
Mr.doob 已提交
1393

1394 1395
		return str;
	}
A
alteredq 已提交
1396 1397
	*/

N
Nicolas Garcia Belmonte 已提交
1398
};